Reputation: 3325
I'm going through this JavaFX tutorial, using Scala as the implementation language, and ran into an issue with my implicit conversion not being picked up:
class HelloApplication extends Application {
import HelloApplication._
override def start(stage: Stage) {
stage.setTitle("Hello World!")
val btn = new Button()
btn.setText("Say 'Hello World'")
btn.setOnAction(function2EventHandler(buttonPressed))
val root = new StackPane()
root.getChildren.add(btn)
stage.setScene(new Scene(root, 300, 250))
stage.show()
}
def buttonPressed(ev: ActionEvent) {
println("Hello World!")
}
}
object HelloApplication {
implicit def function2EventHandler[A <: Event](f: A => Unit): EventHandler[A] =
new EventHandler[A] {
override def handle(t: A) = f(t)
}
}
When I change this line
btn.setOnAction(function2EventHandler(buttonPressed))
to
btn.setOnAction(buttonPressed)
I'm getting a compilation error. Can you point me to what I'm doing wrong?
I'm using the JavaFX that ships with JDK 7 and Scala 2.11.4.
Upvotes: 1
Views: 82
Reputation: 2769
First what I see, that: buttonPressed
is an expression of method type NOT function type
def buttonPressed(ev: ActionEvent) {
println("Hello World!")
}
I think you need to use eta expansion (§6.26.5 Eta Expansion ScalaReference) before implicit conversion:
btn.setOnAction(buttonPressed _)
Upvotes: 5