Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate an instance of type represented by type parameter in Scala

example:

import scala.actors._   import Actor._    class BalanceActor[T <: Actor] extends Actor {     val workers: Int = 10      private lazy val actors = new Array[T](workers)      override def start() = {       for (i <- 0 to (workers - 1)) {         // error below: classtype required but T found         actors(i) = new T         actors(i).start       }       super.start()     }     // error below:  method mailboxSize cannot be accessed in T   def workerMailboxSizes: List[Int] = (actors map (_.mailboxSize)).toList   .   .   .   

Note the second error shows that it knows the actor items are "T"s, but not that the "T" is a subclass of actor, as constrained in the class generic definition.

How can this code be corrected to work (using Scala 2.8)?

like image 789
scaling_out Avatar asked Aug 20 '09 11:08

scaling_out


People also ask

Is it possible to create instances of type parameters?

Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

How do I create an instance of a class in Scala?

Defining a classThe keyword new is used to create an instance of the class. We call the class like a function, as User() , to create an instance of the class.

What is type parameter in Scala?

Language. Methods in Scala can be parameterized by type as well as by value. The syntax is similar to that of generic classes. Type parameters are enclosed in square brackets, while value parameters are enclosed in parentheses.

How do you create an instance of a type in Java?

If you need a new instance of a type argument inside a generic class then make your constructors demand its class... public final class Foo<T> { private Class<T> typeArgumentClass; public Foo(Class<T> typeArgumentClass) { this.


1 Answers

EDIT - apologies, I only just noticed your first error. There is no way of instantiating a T at runtime because the type information is lost when your program is compiled (via type erasure)

You will have to pass in some factory to achieve the construction:

class BalanceActor[T <: Actor](val fac: () => T) extends Actor {   val workers: Int = 10    private lazy val actors = new Array[T](workers)    override def start() = {     for (i <- 0 to (workers - 1)) {       actors(i) = fac() //use the factory method to instantiate a T       actors(i).start     }     super.start()   } }  

This might be used with some actor CalcActor as follows:

val ba = new BalanceActor[CalcActor]( { () => new CalcActor } ) ba.start 

As an aside: you can use until instead of to:

val size = 10 0 until size //is equivalent to: 0 to (size -1) 
like image 111
oxbow_lakes Avatar answered Sep 28 '22 21:09

oxbow_lakes