11

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
5
  • 3
    What's the error message? Commented Apr 27, 2017 at 17:43
  • What compiler error? I don't see any compiler error with the code above. scala> val task: Runnable = () => {System.out.println("Task is running")} gives task: Runnable = $$Lambda$1011/1678449328@2917b6cb Commented Apr 27, 2017 at 17:44
  • What Scala version? Commented Apr 27, 2017 at 17:45
  • Scala uses plain println(), by the way Commented Apr 27, 2017 at 17:45
  • Scala version is 2.11. As commented by Raman below.. I guess 2.12 solves this. Thx. Commented Apr 27, 2017 at 18:00

1 Answer 1

19

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.