Class type required, but T found

I cannot create an actor for any reason (here is a simple version of my class hierarchy):

abstract class Class1[T <: Class2[_]: ClassTag] extends Actor { //.... val res = List(1, 2, 3) map { x => context actorOf Props(new T(x)) } // error } abstract class Class2[U <: Class3 : ClassTag](a: Int) extends Actor { ... } abstract class Class3(b: Int) extends Actor 

But there is an error saying class type required but T found .

+7
scala akka
source share
3 answers

You cannot call new T(x) with a parameter of type T There can be no such constructor for T :

 class WithoutSuchConstructor extends Class2[Class3](1) 

You must specify a method to create T explicitly:

 abstract class Class1[T <: Class2[_]: ClassTag] extends Actor { //.... def createT(i: Int): T val res = List(1, 2, 3) map { x => context actorOf Props(createT(x)) } } 

As an alternative:

 abstract class Class1[T <: Class2[_]: ClassTag](createT: Int => T) extends Actor { //.... val res = List(1, 2, 3) map { x => context actorOf Props(createT(x)) } } 
+8
source share

One approach that I have used is to create the “instantmator” attribute, which can be used to instantiate types for which an implicit instance exists:

 trait Instantiator[+A] { def apply(): A } object Instantiator { def apply[A](create: => A): Instantiator[A] = new Instantiator[A] { def apply(): A = create } } class Foo() { ... } object Foo { implicit val instantiator: Instantiator[Foo] = Instantiator { new Foo() } } // def someMethod[A]()(implicit instantiator: Instantiator[A]): A = { def someMethod[A : Instantiator](): A = { val a = implicitly[Instantiator[A]].apply() ... } someMethod[Foo]() 
+5
source share

I think this is due to the limitation of the JVM, also known as type erasure. http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

also see “Unable to instantiate type parameters” at http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html

By the way, C # allows you to write:

 new T() 

when you define a limit

 where T: new() 

but, unfortunately, the constructor must be without parameters

+1
source share

All Articles