当前位置:首页 > 开发 > 编程语言 > Scala > 正文

【Scala十五】Scala核心九:隐式转换之二

发表于: 2015-02-27   作者:bit1129   来源:转载   浏览:
摘要: 隐式转换存在的必要性,   在Java Swing中,按钮点击事件的处理,转换为Scala的的写法如下:   val button = new JButton button.addActionListener( new ActionListener { def actionPerformed(event: ActionEvent) {

隐式转换存在的必要性,

 

在Java Swing中,按钮点击事件的处理,转换为Scala的的写法如下:

 

val button = new JButton
button.addActionListener(
    new ActionListener {
        def actionPerformed(event: ActionEvent) {
            println("pressed!")
        }
    }
)

 这是典型的Java-Style的代码,虽然使用Scala语法去写的,这个代码,真正有用的只有一句,println("pressed")

 

 

改写一下:

button.addActionListener((_: ActionEvent) => println("pressed!"))

 但是编译失败,原因是addActionListener方法只能接受ActionListener对象作为参数,而不能使用函数常量作为参数,为了消除这种gap,就得定义隐式转换,将函数(确切的说,是将带有ActionEvent类型的参数的函数)转换为ActionListener对象

 

implicit def function2ActionListener(f: ActionEvent => Unit) =
  new ActionListener {
       def actionPerformed(event: ActionEvent) = f(event) //直接赋值
  }
) 

 

隐式转换的工作流程:

The way this code works is that the compiler first tries to compile it as is, but it sees a type error. Before giving up, it looks for an implicit conversion that can repair the problem. In this case, it finds function2ActionListener. It tries that conversion method, sees that it works, and moves on.

 

implicit修饰符可以作用变量、function,class和object上

 

隐式转换的规则:

1. Marking Rule: Only definitions marked implicit are available

2. Scope Rule: An inserted implicit conversion must be in scope as a single identifier, or be associated with

the source or target type of the conversion.

3. One-at-a-time Rule: Only one implicit is tried

4. Explicits-First Rule: Whenever code type checks as it is written, no implicits are attempted.

如果编译时没有类型错误,Scala编译器就不会启动隐式转换功能,即使有满足条件的隐式转换存在

 

 

 

 

 

 

 

【Scala十五】Scala核心九:隐式转换之二

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号