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?
SAM types are supported using invokeDynamic since scala-2.12 similar to JDK-8, Below was tested on 2.12.3 - Release notes about SAM can be found here - http://www.scala-lang.org/news/2.12.0/
Scala has experimental support for SAMs starting with 2.11, under the flag
-Xexperimental
:Edit: Since 2.11.5, this can also be done inline:
The usual limitations about the expected type also apply:
According to the original commit by Adriaan, some of those restrictions may be lifted in the future, especially the last two.
While doing this in a generic way is certainly complicated, if you found that you really only needed this for a few certain Java types, then a few simple implicit conversions can do the job nicely. For instance:
Sometimes trying to solve a problem in a generic and completely re-useable way is the wrong approach if your actual problem is more bounded then you think.