Scala ActionListener /匿名函数类型不匹配

Pet*_*erT 6 scala type-conversion higher-order-functions

尝试实现类似于http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-6中的高阶函数示例中的代码

val button = new JButton("test")
button.addActionListener{ e:ActionEvent => println("test") }
add(button)
Run Code Online (Sandbox Code Playgroud)

导致以下内容

error: type mismatch;
found   : (java.awt.event.ActionEvent) => Unit 
required: java.awt.event.ActionListener
   button.addActionListener{ e:ActionEvent => println("test") }
                                           ^
Run Code Online (Sandbox Code Playgroud)

至少在我的系统上使用Scala编译器版本2.7.6.final时这是真的.我能够以Java风格的方式实现我想要的显式实现匿名ActionListener.

button.addActionListener( new ActionListener() {
  def actionPerformed(e:ActionEvent) { println("test") }
})
Run Code Online (Sandbox Code Playgroud)

据我所知,Scala应该能够使用duck-typing来渲染ActionListener的显式实现; 那为什么不在这里工作?在这一点上,我几乎没有鸭子打字的实际​​经验.

kmi*_*izu 11

鸭子打字与你的代码不起作用的原因无关.这是因为Scala的类型系统默认情况下不提供接口类型和函数类型之间的隐式转换.但是,如果定义了以下隐式转换,则代码可以正常工作.

implicit def toActionListener(f: ActionEvent => Unit) = new ActionListener {
  def actionPerformed(e: ActionEvent) { f(e) }
}
Run Code Online (Sandbox Code Playgroud)

此隐式转换提供从(ActionEvent => Unit)到ActionListner的转换.