Reputation: 714
Given the following pair of overloaded functions:
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)
}
}
When trying to use the assignment method as such
onAction = { ae => doSomething() }
Scala complains about a missing type parameter for ae
. Why is Scala unable to infer the type of ae
since only one of the overloads takes a function type, and thus there is no confusion about which method to call.
Does the Scala compiler simply give up on trying to infer types when it sees an overloaded function?
P.S. As an interesting aside, the IntelliJ Scala plugin is able to resolve the type of ae
to be that of ActionEvent
. I'm amused at the plugin being able to do something the compiler cannot, or does not.
Upvotes: 2
Views: 156
Reputation: 3519
I think you are missing a getter/accessor. You can't have a setter without a getter. Here is a complete example which compiles:
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 = ???
}
Upvotes: 1