Scala-解析模板化类型
我有一个模板类,根据T的类型,我想打印一些不同的内容Scala-解析模板化类型,scala,Scala,我有一个模板类,根据T的类型,我想打印一些不同的内容 class Clazz[T](fn: T => String) {} 理想情况下,我想做一些类似于模式匹配T的事情(我做不到): 我试过: class Clazz[T](fn: T => String) { def resolve():String = fn match { case f:(Int => String) => println("function from int to string")
class Clazz[T](fn: T => String) {}
理想情况下,我想做一些类似于模式匹配T的事情(我做不到):
我试过:
class Clazz[T](fn: T => String) {
def resolve():String = fn match {
case f:(Int => String) => println("function from int to string")
case _ => //...etc.
}
}
我得到的错误信息是:
non-variable type argument Int in type pattern Int => String is unchecked since it is eliminated by erasure
有办法解决这个问题吗?我会使用
TypeTag
,这样我就可以在不丢失任何类型信息的情况下将T
与其他类型进行比较:
import scala.reflect.runtime.universe._
class Clazz[T: TypeTag](fn: T => String) {
val resolve = typeOf[T] match {
case t if t =:= typeOf[Int] => "function from Int to String"
case t if t =:= typeOf[Byte] => ..
}
}
但是,如果我只是想打印出与toString
不同的内容,我会使用类型类:
trait Print[T] {
def toText(t: T): String
def apply(t: T) = print(toText(t))
}
def print[T: Print](t: T) = implicitly[Print[T]].apply(t)
implicit object PrintInt extends Print[Int] {
def toText(t: Int) = s"Int: $t"
}
implicit object PrintByte extends Print[Byte] {
def toText(t: Byte) = s"Byte: $t"
}
PrintInt(3) //=> Int: 3
print(3) //=> Int: 3
3.即使添加以下内容,也可以进行打印:
implicit class Printable[T:Print](t: T) {
def print = implicitly[Print[T]].apply(t)
}
3.print //=> Int: 3
我会使用TypeTag
,这样我就可以将T
与其他类型进行比较,而不会丢失任何类型信息:
import scala.reflect.runtime.universe._
class Clazz[T: TypeTag](fn: T => String) {
val resolve = typeOf[T] match {
case t if t =:= typeOf[Int] => "function from Int to String"
case t if t =:= typeOf[Byte] => ..
}
}
但是,如果我只是想打印出与toString
不同的内容,我会使用类型类:
trait Print[T] {
def toText(t: T): String
def apply(t: T) = print(toText(t))
}
def print[T: Print](t: T) = implicitly[Print[T]].apply(t)
implicit object PrintInt extends Print[Int] {
def toText(t: Int) = s"Int: $t"
}
implicit object PrintByte extends Print[Byte] {
def toText(t: Byte) = s"Byte: $t"
}
PrintInt(3) //=> Int: 3
print(3) //=> Int: 3
3.即使添加以下内容,也可以进行打印:
implicit class Printable[T:Print](t: T) {
def print = implicitly[Print[T]].apply(t)
}
3.print //=> Int: 3
谢谢唯一需要注意的是:它不应该是“typeOf[T].tpe match”,而应该是“typeOf[T]match”,谢谢。唯一需要注意的是:它不应该是“typeOf[T].tpe-match”,而应该是“typeOf[T]match”