我希望能够在 scala 中定义这样一个好的接收函数
sealed trait DoParent
case object DoThis extends DoParent
case object DoThat extends DoParent
object MyApp extends App {
val receive = {
case DoThis => println("dothis")
case DoThat => println("dothat")
}
receive(DoThis)
}
但它会生成
missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
val receive = {
^
我现在明白它要求我添加类型,但我希望接收看起来像 Actor 接收的样子一样整洁干净(仅定义内部的情况,如图所示,没有类型),我缺少什么?
谢谢
最佳答案
我怀疑是否有办法绕过类型规范。 Actor 这样做的方式是他们在父特征中声明接收,例如:
trait WithReceive {
def receive:PartialFunction[DoParent, Unit] //for some reason this needs to be a def
}
然后让你的对象继承该特征:
object MyApp extends App with WithReceive {
def receive = { //this needs to be a def too
case DoThis => ???
case DoThat => ???
}
}
出于某种原因,它需要是一个 def,使用 val 会导致与您得到的错误相同的结果。
关于scala - 无需指定输入类型即可定义高阶函数的巧妙方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22403421/