例:
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
.
.
.
Run Code Online (Sandbox Code Playgroud)
注意第二个错误表明它知道actor项是"T",但不是"T"是actor的子类,而是在类通用定义中受到约束.
如何纠正此代码(使用Scala 2.8)?
我正在尝试做一些我不确定Scala的类型系统是否允许我这样做的事情.
我基本上想要从泛型定义创建一个闭包并返回该闭包,同时在同一类型内部执行一个函数.
例如:
val f = async[(str:String, i:Int, b:BigInt) => Unit]({ (String, Int, BigInt) =>
// Code here...
})
// 'f' would have a type of (String, Int, BigInt) => Unit and would wrap the passed anonymous function
Run Code Online (Sandbox Code Playgroud)
定义的理论范例:
def async[T](
shell: Shell,
success: T,
failure: (Throwable) => Unit): T = {
new T {
val display = shell.getDisplay()
display.asyncExec(new Runnable() {
def run(): Unit = {
try {
success(_)
} catch {
case e:Throwable =>
failure(e)
} …Run Code Online (Sandbox Code Playgroud)