Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking toString via method reference in Java 8

What am I missing? Why do I have to use Object::toString below and not Integer::toString? Does it have anything to do with type erasure with generics?

Arrays.asList(1,2,3).stream().map(Integer::toString).forEach(System.out::println); //Won't compile

Arrays.asList(1,2,3).stream().map(Object::toString).forEach(System.out::println); //Compiles and runs fine
like image 379
sat Avatar asked Jan 11 '15 08:01

sat


1 Answers

This has nothing to do with type erasure.

Look at the error message :

(argument mismatch; invalid method reference
  reference to toString is ambiguous
    both method toString(int) in Integer and method toString() in Integer match)

The Integer class has two toString methods that match the functional interface expected by the map() method. One is static with an int argument, and the other is the toString() method that overrides Object's toString().

The compiler doesn't know if you want to execute this :

Arrays.asList(1,2,3).stream().map(i->Integer.toString(i)).forEach(System.out::println);

or this :

Arrays.asList(1,2,3).stream().map(i->i.toString()).forEach(System.out::println);
like image 162
Eran Avatar answered Nov 18 '22 18:11

Eran