Scala单方法接口实现 [英] Scala single method interface implementation

查看:131
本文介绍了Scala单方法接口实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala是否有任何语法糖来替换以下代码:

Does Scala have any syntactic sugar to replace the following code:

val thread = new Thread(new Runnable {
   def run() {
     println("hello world")
   }    
})

更像是:

val thread = new Thread(() => println("hello world"))

在特征/接口只需要实现一种方法的情况下?如果没有,将来是否有机会在Scala中使用此功能?当处理Java类时,它特别有用。

in cases when the trait/interface needs only one method to be implemented? If not, is there any chance to have this feature in Scala in the future? It is especially useful when one deals with Java classes.

我在三年前发现了一个类似的问题:通常使用Scala闭包实现Java Single-Abstract-Method接口?答案说我们应该具有Scala 2.10中的功能。我找了单一抽象方法关键字,但我没有找到任何东西。该功能发生了什么?

I found a similar question asked three years ago: Generically implementing a Java Single-Abstract-Method interface with a Scala closure? The answer says we should have the feature in Scala 2.10. I've looked for Single Abstract Method keyword but I have not found anything. What's happened with the feature?

推荐答案

Scala拥有实验性支持从2.11开始的SAM, flag -Xexperimental

Scala has experimental support for SAMs starting with 2.11, under the flag -Xexperimental:

Welcome to Scala version 2.11.0-RC3 (OpenJDK 64-Bit Server VM, Java 1.7.0_51).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :set -Xexperimental

scala> val r: Runnable = () => println("hello world")
r: Runnable = $anonfun$1@7861ff33

scala> new Thread(r).run
hello world

编辑 :从2.11.5开始,这也可以内联完成:

Edit: Since 2.11.5, this can also be done inline:

scala> new Thread(() => println("hello world")).run
hello world

关于预期类型的​​通常限制也适用:

The usual limitations about the expected type also apply:


  • 它必须定义一个抽象方法,

  • 其主要构造函数(如果有)必须是public,no-args,not overloaded,

  • 抽象方法必须采用单个参数列表,

  • 抽象方法必须是单态的。

  • it must define a single abstract method,
  • its primary constructor (if any) must be public, no-args, not overloaded,
  • the abstract method must take a single argument list,
  • the abstract method must be monomorphic.

根据原始提交,其中一些限制可能在将来解除,特别是最后两个。

According to the original commit by Adriaan, some of those restrictions may be lifted in the future, especially the last two.

这篇关于Scala单方法接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆