Given the code fragment:
String str = "Say what?!"; ToIntFunction<String> indx = str::indexOf; //line n1 int a = indx.applyAsInt("Say"); //line n2 System.out.println(a);
What is the result?
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2
The correct answer is A.
This question demonstrates how the so-called bound method references work. Read a more comprehensive discussion on metrefs here (note so self: write it.)
All options have no inherent contradictions in them and are equally possible, so we’ll start our analysis by checking if the code flags a comperr somewhere. Line n1 appears to be clean: the java.util.function package does include a ToIntFunction class, which is a primitive specialization of a BiFunction. Since it’s a function, it returns a value and must be supplied with an argument. Well, this is exactly what we observe here: str is the function’s arg, and String’s indexOf() returns an int.
What about line n2? Apparently, it is fine, too. The functional methods in all “functions” in java.util.function are called apply(), with a suffix that reflects primitive type in case of primitive specializations, such as applyAsLong() in ToLongFunction or applyAsDouble() in ToDoubleFunction. There are no exceptions to this rule, it is fully consistent and, therefore, easily memorizable. A very good news for us exam takers, a very good news indeed.
Okay, so it seems the code compiles, and since “Say what?!“.indexOf(“Say“) returns 0, we finally arrive at the correct answer.