Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[eclipse-dev] Java: Overloading & Lambdas = TROUBLE

Hi folks,

As your compiler engineer, and alarmed by a recent event, I have to warn you that Java 8 brought one particularly nasty pitfall: If your API defines same-named methods which differ only in the type of a parameter, and if that type is a functional interface you are effectively requiring that all users of this API need to understand details of Java which I wish they would never need to think about:

First you need to teach all users of the API, that type inference in Java 8 happens in several phases, and that overload resolution happens before the final phase. Then you need to teach all users of that API, that some functional expressions (lambdas, method references, under certain conditions) are not pertinent to applicability. If they confirm that they understand JLS sections §15.12, §15.13, §15.27 and all of §18, then they may get the license to invoke your API.

I'm not kidding. Overloading in Java was problematic well before Java 8, in terms of: it's very easy to write programs which seasoned Java programmers will not understand. Java 8 "improved" this by the above problem.

The general problem can surface in two ways: perhaps the compiler says that a given method invocation is ambiguous. In that case be happy about this alert and write your code in a way that not for a fraction of a second anybody will have to guess which of the methods will be invoked (explicit type arguments etc pp).

If the compiler accepts the method invocation, you may be in trouble, because your intuition about which method will be chosen by the compiler may very well be wrong. Not knowing which method a given call will invoke doesn't sound very nice, right?

In the particular, recent event, it is likely too late to change the affected API, but please refrain from adding more like that - and be extra careful when using API that is already affected.


Back to the top