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

3

47

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?

Disproportionation answered 19/2, 2014 at 7:28 Comment(2)
Did you try to change map to mapToInt?Advised
@Advised that wouldn't be applicable. we're mapping to strings, from ints.Tallia
L
55

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.

Lapland answered 19/2, 2014 at 9:25 Comment(0)
J
34

Since Integer.toString() overrides Object.toString(), in this particular case you could fix it as follows:

Stream.of(1, 32, 12, 15, 23).map(Object::toString);
Jeanajeanbaptiste answered 25/7, 2016 at 7:13 Comment(0)
E
23

Your main options, using method references, are:

Stream.of(1, 32, 12, 15, 23).map(String::valueOf);
IntStream.of(1, 32, 12, 15, 23).mapToObj(Integer::toString);

Your current version could mean i -> i.toString() or i -> Integer.toString(i).

Exegete answered 19/2, 2014 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.