简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM