加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 19:09:40 所属栏目:安全 来源:网络整理
导读:尝试实现类似于 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 mism
尝试实现类似于 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应该能够使用duck-typing来渲染ActionListener的显式实现;那为什么不在这里工作?在这一点上,我几乎没有鸭子打字的实际??经验.

解决方法

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

implicit def toActionListener(f: ActionEvent => Unit) = new ActionListener {
  def actionPerformed(e: ActionEvent) { f(e) }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读