Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

Scala single method interface implementation

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

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

with something more like:

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

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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:

  • 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...