如何在 Scala 中实例化由类型参数表示的类型实例 [英] How to instantiate an instance of type represented by type parameter in Scala
问题描述
示例:
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
.
.
.
注意第二个错误表明它知道actor项是T",但不知道T"是actor的子类,如类泛型定义中的约束.
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.
如何更正此代码以使其正常工作(使用 Scala 2.8)?
How can this code be corrected to work (using Scala 2.8)?
推荐答案
EDIT - 抱歉,我才注意到你的第一个错误.无法在运行时实例化 T
,因为编译程序时类型信息会丢失(通过类型 擦除)
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()
}
}
这可能与某些演员 CalcActor
一起使用,如下所示:
This might be used with some actor CalcActor
as follows:
val ba = new BalanceActor[CalcActor]( { () => new CalcActor } )
ba.start
顺便说一句:您可以使用 until
而不是 to
:
As an aside: you can use until
instead of to
:
val size = 10
0 until size //is equivalent to:
0 to (size -1)
这篇关于如何在 Scala 中实例化由类型参数表示的类型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!