[英]Scala ClassTag & classOf and type parameter. Strange case of generics
Here is my code straight & simple: 这是我的代码简单明了:
package scalaproj
import scala.reflect._
case class MyClass() {}
def bar[T](cls : Class[T]) = println(cls)
def foobar[T: ClassTag] = println(classTag[T])
bar(classOf[MyClass])
foobar[MyClass]
Results: class scalaproj.GetFields$MyClass$2
scalaproj.GetFields$MyClass$2
Now I would like to do the following without the famous error: "class type required but T found" 现在,我要执行以下操作而不会出现著名的错误:“需要类类型但找到了T”
def foo[T] = println(classOf[T])
foo[MyClass]
foo is just a function that takes a Generic Type Parameter and does not need a value parameter. foo只是一个带有通用类型参数的函数,不需要值参数。 I think this is strange given the two examples that work and all the flexibility build in into the Scala language and its handeling of generics.
考虑到两个有效的示例以及Scala语言及其通用泛型的所有灵活性,我认为这很奇怪。
Update: 更新:
Just to specify further strangeness: 只是为了进一步说明奇怪之处:
def foo1[T](t : T) = {} // no compile error
def foo2[T](): List[T] = { List[T]() } // no compile error
def foo3[T](): T = { T() } // compile error: "not found: value T"
A good explanation is appreciated. 一个很好的解释表示赞赏。
You can't, as classOf
will not work with arbitrary types (and your T
is an arbitrary type). 您不能这样做,因为
classOf
不适用于任意类型(并且您的T
是任意类型)。
For example: 例如:
scala> classOf[Int with String]
<console>:15: error: class type required but Int with String found
classOf[Int with String]
^
You can achieve the same thing with ClassTag#runtimeClass
: 您可以使用
ClassTag#runtimeClass
实现相同的ClassTag#runtimeClass
:
def foo[T: ClassTag] = println(classTag[T].runtimeClass)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.