【发布时间】:2010-07-13 16:15:01
【问题描述】:
尝试实现类似于 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)
导致以下内容
error: type mismatch;
found : (java.awt.event.ActionEvent) => Unit
required: java.awt.event.ActionListener
button.addActionListener{ e:ActionEvent => println("test") }
^
至少对于我系统上的 Scala 编译器版本 2.7.6.final 来说是这样。我能够以 Java 风格的方式显式实现匿名 ActionListener 来实现我想要的。
button.addActionListener( new ActionListener() {
def actionPerformed(e:ActionEvent) { println("test") }
})
据我了解,Scala 应该能够使用鸭子类型来使 ActionListener 的这种显式实现变得不必要;那么为什么它不在这里工作呢?在这一点上,我几乎没有鸭子打字的实际经验。
【问题讨论】:
标签: scala type-conversion higher-order-functions