Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a trait expression to single abstract method

Tags:

scala

Say I define the following:

trait T {
    def foo(): Int
}

def bar(t: T): Int = {
    t.foo()
}

bar(new T {
    def foo() = 3
})

The compiler gives me the warning:

Convert expression to Single Abstract Method

But when I try

bar(new T(() => 3))

I get the error

T is a trait and thus has no constructor

Can a trait be converted to a single abstract method?

like image 287
user79074 Avatar asked May 11 '19 13:05

user79074


1 Answers

You just need this:

bar(() => 3)

SAM in Scala is something similar to FunctionalInterface in Java. So if your trait/abstract class has only one abstract method to be defined it is treated as SAM(single abstract method) type and can be written just as simple lambda.

It would also work for variable assignments:

val a = () => 3 // compiler would infer () => Int for a
val b: T = () => 3 // type of b is T
like image 158
Krzysztof Atłasik Avatar answered Oct 17 '22 11:10

Krzysztof Atłasik