Stream.flatMap reference ambiguity
Zhong Yu
zhong.j.yu at gmail.com
Tue Feb 26 09:06:09 PST 2013
On Tue, Feb 26, 2013 at 7:57 AM, David Hartveld <david at hartveld.net> wrote:
> Hi all,
>
> I just ran into the following problem with flatMap: the compiler
> (lambda-b78) is not able to infer the correct overload for flatMap.
>
> The code:
>
> List<String> ss = new ArrayList<>();
> ss.stream().flatMap((x, sink) -> {
> for (String s : x.split(",")) {
> sink.accept(s);
> }
> });
This example is not very realistic, since the result of flatMap() is
not used, the code doesn't really do anything. What if it's assigned
to a `Stream<String>`?
> The compiler output:
>
> FlatMapTest.java:[38,28] reference to flatMap is ambiguous
> both method flatMap(java.util.stream.FlatMapper.ToLong<? super T>) in
> java.util.stream.Stream and method
> flatMap(java.util.stream.FlatMapper.ToDouble<? super T>) in
> java.util.stream.Stream match
> FlatMapTest.java:[40,37] method accept in interface
> java.util.function.LongConsumer cannot be applied to given types;
> required: long
> found: java.lang.String
> reason: argument mismatch; java.lang.String cannot be converted to long
>
> This can be solved by typing the lambda parameters (actually, exactly that
> is done in the default implementation of Stream.flatMap(Function<T,
> Stream<? extends R>>).
>
> Is this a bug/unimplemented inference situation? If not, I would prefer a
> rename of the flatMap overloads that return a primitive stream (these cause
> the ambiguity, right?). I think it is confusing that, when using the Stream
> API (or any other coherent API), you have to specify types in some lambdas,
> and not in others - I find this confusing, and it probably is even more so
> for less advanced programmers.
>
> Thanks in advance for a great-looking update to the JDK!
>
> Regards,
> David Hartveld
>
More information about the lambda-dev
mailing list