简体   繁体   中英

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"

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. 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.

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).

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 :

def foo[T: ClassTag] = println(classTag[T].runtimeClass)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM