user79074
user79074

Reputation: 5270

How to convert a trait expression to single abstract method

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?

Upvotes: 5

Views: 749

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

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

Upvotes: 6

Related Questions