Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java vs Scala Functional Interface Usage

Tags:

java

scala

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
like image 998
Apurva Singh Avatar asked Apr 27 '17 17:04

Apurva Singh


People also ask

What is real time use of functional interface in Java?

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.

What is the use of Java functional interface?

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.

Is Java comparable functional interface?

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.

Why do we need functional interfaces?

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.


1 Answers

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.

like image 64
Raman Avatar answered Sep 19 '22 06:09

Raman