Java vs Scala Functional Interface Usage

Apurva Singh :

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
Raman :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441555&siteId=1