When doing this
Stream.of(1, 32, 12, 15, 23).map(Integer::toString);
I get an ambiguous type error. Understandably, the compiler can't tell if I mean toString(int)
or toString()
from Integer
.
When not using a method reference, I might have gotten out of this with an explicit cast or write out the generics long hand, but how can I let the compiler know what I mean here? What syntax (if any) can I use to make in unambiguous?
This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.
Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Here is an example that involves method overloading: Notice that MyGenClass declares two generic types: T and V.
If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference. In the first two cases, the method reference is equivalent to lambda expression that supplies the parameters of the method e.g. System.
There is no way to make method references unambiguous; simply said, method references are a feature that is just supported for unambiguous method references only. So you have two solutions:
use a lambda expression:
Stream.of(1, 32, 12, 15, 23).map(i->Integer.toString(i));
(preferred, at least by me) Use a stream of primitive int
values when the source consists of primitive int
values only:
IntStream.of(1, 32, 12, 15, 23).mapToObj(Integer::toString);
This will use the static Integer.toString(int)
method for consuming the int
values.
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