如何在子类中实现偏函数

发布于 2024-09-08 21:28:48 字数 844 浏览 1 评论 0原文

我正在尝试设计几个继承部分函数的类,但我似乎无法使语法完全正确。我的超类看起来像这样:

abstract class Controller {

    val react:PartialFunction[Event,Unit]

}

子类看起来像:

class BoardRendererController(val renderer:BoardRenderer, val board:Board) extends Controller {

    override val react {
        case PieceMovedEvent(piece, origin, destination) => println("Moving now")
    }
}

但这无法编译并出现此错误

[ERROR] /workspace/pacman/src/main/scala/net/ceilingfish/pacman/BoardRendererController.scala:14: error: '=' expected but '{' found.
[INFO]  override val react {
[INFO]                            ^
[ERROR] /workspace/pacman/src/main/scala/net/ceilingfish/pacman/BoardRendererController.scala:17: error: illegal start of simple expression
[INFO] }
[INFO] ^

我已经尝试了很多变体,有人知道正确的语法是什么吗?

I'm trying to design a couple of classes that inherit a partial function, but I don't seem to be able to get the syntax quite right. My superclass looks like this:

abstract class Controller {

    val react:PartialFunction[Event,Unit]

}

And the subclass looks like:

class BoardRendererController(val renderer:BoardRenderer, val board:Board) extends Controller {

    override val react {
        case PieceMovedEvent(piece, origin, destination) => println("Moving now")
    }
}

But this fails to compile with this error

[ERROR] /workspace/pacman/src/main/scala/net/ceilingfish/pacman/BoardRendererController.scala:14: error: '=' expected but '{' found.
[INFO]  override val react {
[INFO]                            ^
[ERROR] /workspace/pacman/src/main/scala/net/ceilingfish/pacman/BoardRendererController.scala:17: error: illegal start of simple expression
[INFO] }
[INFO] ^

I've tried loads of variations on this, anyone know what the correct syntax is?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

强者自强 2024-09-15 21:28:48

除了 abhin4v 的简洁建议之外,您仍然必须在定义中提供类型注释,因此我建议在您的基类中添加此内容:

type PFEU = PartialFunction[Event, Unit]

那么您的子类将如下所示:

class BoardRendererController(val renderer:BoardRenderer, val board:Board)
extends Controller
{
    override val react: PFEU = {
        case PieceMovedEvent(piece, origin, destination) => println("Moving now")
    }
}

In addition to abhin4v's terse suggestion, you still have to supply a type annotation in the definition, so I recommend this addition to your base class:

type PFEU = PartialFunction[Event, Unit]

Then your subclass would look like this:

class BoardRendererController(val renderer:BoardRenderer, val board:Board)
extends Controller
{
    override val react: PFEU = {
        case PieceMovedEvent(piece, origin, destination) => println("Moving now")
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文