Lambdas and SAM types

Java has numerous functional interfaces that have only one method. They are called SAM types, which stands for Single Abstract Method. One example of that kind of interface is IntPredicate from the Java standard library:

@FunctionalInterface
public interface IntPredicate {

/**
* Evaluates this predicate on the given argument.
*
* @param value the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(int value);
}

In the next example, we are trying to create this interface with a lambda, but the compiler will throw an error:

fun createPredicate(): IntPredicate {
//compiler error
return { n: Int -> n % 2 == 0 }
}

Even though the function signature of the interface and the lambda match—they both accept an int as the parameter and return a Boolean—the compiler is complaining because in the lambda return statement, it sees a function type of Function1 but IntPredicate is needed.

To make it compile, we have to put the name of the interface before the lambda expression, similar to casting a type but without parentheses:

fun createPredicate(): IntPredicate {
return IntPredicate { n -> n % 2 == 0 }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.107.85