给定以下两个重载函数:
def onAction_=(implicit aeh: jfxe.EventHandler[jfxe.ActionEvent]) {
onAction() = aeh
}
def onAction_=(handler: ActionEvent => Unit): Unit = {
onAction() = new jfxe.EventHandler[jfxe.ActionEvent] {
override def handle(event: jfxe.ActionEvent): Unit = handler(event)
}
}当尝试像这样使用赋值方法时
onAction = { ae => doSomething() }Scala抱怨ae缺少类型参数。为什么Scala无法推断ae的类型,因为只有一个重载采用函数类型,因此不会混淆调用哪个方法。
另外,有趣的是,IntelliJ Scala插件能够将ae类型解析为ActionEvent类型。我很高兴这个插件可以做编译器不能做的事情,或者不能做的事情。
发布于 2015-05-04 01:51:05
我想你遗漏了一个getter/访问器。没有getter就不能有setter。下面是一个完整的例子,它编译如下:
import javafx.{ event => jfxe }
class Foo {
private var _onAction: jfxe.EventHandler[jfxe.ActionEvent] = _
def onAction = _onAction // the getter is necessary!
def onAction_=(implicit aeh: jfxe.EventHandler[jfxe.ActionEvent]) {
_onAction = aeh
}
def onAction_=(handler: jfxe.ActionEvent => Unit): Unit = {
_onAction = new jfxe.EventHandler[jfxe.ActionEvent] {
override def handle(event: jfxe.ActionEvent): Unit = handler(event)
}
}
}
object Driver extends App {
val f = new Foo
f.onAction = { ae => doSomething() }
def doSomething(): Unit = ???
}https://stackoverflow.com/questions/30016816
复制相似问题