In Java I can do this:
Runnable task = () -> { System.out.println("Task is running"); };
But how come in Scala I can't do the same!
val task: Runnable = () => {println("Task is running")}
I get a compiler error! I am using Scala version 2.11.8.
type mismatch; found : () => Unit required: Runnable
Further, due to the fact that we can use functional interfaces as target types for lambda expressions & methods references, this would be useful when: passing a comparator to a sort method e.g. List. sort , Stream. sorted , Collections.
Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. Functional interfaces are interfaces that ensure that they include precisely only one abstract method.
Comparable is also a functional interface since it also has a single abstract method. How- ever, using a lambda for Comparable would be silly. The point of Comparable is to imple- ment it inside the object being compared.
A functional interface is an interface that contains only a single abstract method (a method that doesn't have a body). The main reason why we need functional interfaces is that we can use them in a lambda expression and method references. This way we reduce boilerplate code.
Scala version 2.12 supports converting lambda expressions to types with a "single abstract method" (SAM), aka "Functional Interface", like Java 8 does. See http://www.scala-lang.org/news/2.12.0#lambda-syntax-for-sam-types.
Earlier Scala versions are not capable of automatically converting the lambda expression to a Java functional interface / SAM type (such as Runnable
). You are most likely using a version prior to 2.12.
The code you provided works perfectly fine in Scala 2.12.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With