gpt4 book ai didi

scala - 扩展 Scala Actor

转载 作者:行者123 更新时间:2023-12-04 22:09:19 25 4
gpt4 key购买 nike

我是 Scala 的新手。在学习Actor的时候,我尝试对其进行扩展,以节省一行def:

import scala.actors.Actor
import Actor._
class Actoo(actoo: =>Unit) extends Actor {
def act() {actoo}
}
object run extends Application {
/*
// this one runs well
val a = new Actor {
def act() {
receive { case 1 => println("1") }
}
}
*/
val a = new Actoo {
receive { case 1 => println("1") }
}
a.start
a ! 1
}

然后异常跟踪如下所示:
java.lang.AssertionError: assertion failed: receive from channel belonging to other actor
at scala.Predef$.assert(Predef.scala:92)
at scala.actors.Actor$class.receive(Actor.scala:424)
at Actoo.receive(actoo.scala:3)
at run$$anon$1.<init>(actoo.scala:16)
at run$.<init>(actoo.scala:15)
at run$.<clinit>(actoo.scala)
at run.main(actoo.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at scala.tools.nsc.ObjectRunner$$anonfun$run$1.apply(ObjectRunner.scala:75)
at scala.tools.nsc.ObjectRunner$.withContextClassLoader(ObjectRunner.scala:49)
at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:74)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:154)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

可能有很多替代方法可以做同样的事情,但我最好知道上面的代码不起作用的原因。

最佳答案

这很容易。事实上,这种行为不是由于 Actor 库造成的。一段代码

val a = new Actoo {
receive { case 1 => println("1") }
}

被编译器解释为“创建 Actoo 的新实例”,具有初始化主体 receive {...} 并且 val actoo 变得等于 () 。因此,您的代码等效于
val a = new Actoo() {
receive { case 1 => println("1") }
}

为了修复代码,您需要编写
val a = new Actoo ({
receive { case 1 => println("1") }
})

关于scala - 扩展 Scala Actor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1186523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com