Apurva Singh
Apurva Singh

Reputation: 5000

Java vs Scala Functional Interface Usage

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

Upvotes: 11

Views: 4693

Answers (1)

Raman
Raman

Reputation: 19635

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.

Upvotes: 19

Related Questions