2016-07-28 65 views
0

我可以捕捉一些类的类型参数的类型,像这样:如何指定Scala的类型参数约束时,也指定TypeTag

import scala.reflect.runtime.universe._ 

case class X[T:TypeTag]() { 
    val typ = typeOf[T] 
} 

但我怎么可以这样做,如果我想执行一个类型约束:

trait SomeClass 

case class X[T<:SomeClass]() { 
    val typ = typeOf[T] 
} 

这不起作用:

case class X[T<:SomeClass with TypeTag]() { // TypeTag takes parameters 
    val typ = typeOf[T] 
} 

同样没有:

case class X[T<:SomeClass with TypeTag[T]]() { 

    val typ = typeOf[T] 
} 

X[String]()// type arguments [String] do not conform to method apply's type parameter bounds [T <: SomeClass with reflect.runtime.universe.TypeTag[T]] 

回答

1
scala> case class X[T <: SomeClass : TypeTag]() { 
    val typ = typeOf[T] 
} 
defined class X