Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix ambiguous type on method reference (toString of an Integer)?

Tags:

java

java-8

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?

like image 765
Toby Avatar asked Feb 19 '14 07:02

Toby


People also ask

What is ambiguous method call in Java?

This ambiguous method call error always comes with method overloading where compiler fails to find out which of the overloaded method should be used.

What is ambiguous error in Java?

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.

How do you replace lambda expression with method reference?

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.


1 Answers

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:

  1. use a lambda expression:

    Stream.of(1, 32, 12, 15, 23).map(i->Integer.toString(i)); 
  2. (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.

like image 190
Holger Avatar answered Sep 28 '22 01:09

Holger