stella stella - 1 month ago 17
Scala Question

Scala generic Class[_] parameter

I have the following class:

class MyClass[T <: Enum[T]](val clazz: Class[T]){
def dummy = println(clazz.toString)
}


and the following method which is supposed to create
MyClass
objects:

def createMyClass(clazz: Class[_]) =
if(clazz.isEnum)
new MyClass(clazz) //compile error is here
else throw new IllegalArgumentException(s"$clazz is not an enum")


But it refuses to compile. Actually, we pass the object of
Class[_]
which does not satisfy type bounds. Is there a way to tell the compiler that we have actually a
Class
representing a
Enum
.

In Java, I would just do casting, but I suppose Scala has some better way to deal with such things.

BTW,

new MyClass(clazz.asInstanceOf[Class[Enum[_]]])


does not work either

I cannot change methods' signatures.

Answer

I cannot change methods' signatures.

You can do it if necessary, using an existential type

def createMyClass(clazz: Class[_]) =
  if(clazz.isEnum)
    new MyClass(clazz.asInstanceOf[Class[T] forSome { type T <: Enum[T] }])
  else throw new IllegalArgumentException(s"$clazz is not an enum")

But you should carefully consider if it's actually necessary. asInstanceOf should be, if not always last resort, then close to it.