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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With