Java Reference
In-Depth Information
Lambdas with Explicit Typing
Some Java developers just can't bear to part with explicit typing, some code analysis tools (such as IDEs)
need a little extra help from time to time, and sometimes you may even manage to confuse the compiler. 7
In these cases, you need to provide the compiler with explicit types to help it out. When you get to these
cases, it is a sign that something is probably wrong with your API, and you might be best off fixing whatever
ambiguity it is that caused the problem. If you really want to specify your types explicitly, though, you can do
so by using the parenthesized argument list. If you put parentheses around your arguments (even if there is
only one), then you can add explicit types. In Listing 2-15, we see a case that raises some confusion, and how
we can add explicit types to solve it.
Listing 2-15. Using Explicit Typing to Resolve Overloaded Method Ambiguity
public static void main(String[] args) {
// .toUpperCase() exists in String, but not on CharSequence
transform(args[0], (String str) -> str.toUpperCase());
}
public static String transform(
String str,
Function<String, String> transformer
) {
return transformer.apply(str);
}
public static CharSequence transform(
CharSequence str,
Function<CharSequence, CharSequence> transformer
) {
return transformer.apply(str);
}
Lambdas as Operators
Java 8 provides a bit of shorthand for the common case when the types of the arguments and return values
are the same. In this case, you can save repeating yourself by using the “operator functional interfaces.” 8
There are two of these that work on objects: BinaryOperator and UnaryOperator . BinaryOperator is a
BiFunction whose arguments and return types are all the same type; UnaryOperator is a Function whose
arguments and return types are all the same type. Aside from the much more succinct type signature,
there's no difference between these operators and their corresponding functional interfaces. Listing 2-16
demonstrates using the operator types to capture the uppercase and string concatenation lambdas that we
have seen throughout this chapter.
7 As we will see in Listing 2-15, the best way to confuse the compiler is with overloaded methods, especially if you combine
overloaded methods and inheritance. Aside from that, the type inference in the Oracle SDK is actually quite good.
8 If you are looking for Java to allow you to override operators like + and - , you are going to be sorely disappointed. It's
just not something that will make it through the Java Community Process as things stand. You may want to look at the
Java-OO javac plugin, however: http://amelentev.github.io/java-oo/
 
Search WWH ::




Custom Search