组合对特定类型的任意对象的实例方法的引用
Composing references to an instance method of an arbitrary object of a particular type
编译没有错误:
Function<T, List<R>> f = T::getRs;
Function<List<R>, Stream<R>> g = List::stream;
Function<T, Stream<R>> h = f.andThen(g);
List<T> ts = ...;
ts.stream().flatMap(h);
但这会产生错误:
List<T> ts = ...;
ts.stream().flatMap(T::getRs.andThen(List::stream));
错误是:
error: method reference not expected here
.flatMap(T::getRs.andThen((List::stream)))
^
error: invalid method reference
.flatMap(T::getRs.andThen((List::stream)))
^
non-static method stream() cannot be referenced from a static context
where E is a type-variable:
E extends Object declared in interface Collection
我原以为这两种方法是等价的。我缺少一些语法吗?也许在某处分组?如果可能的话,我更愿意采用后一种 "one-line" 方法。
这不是方法参考的正确语法;好像你正在尝试调用这样的东西(注意括号,即使它仍然不正确):
List<T> ts = ...;
ts.stream().flatMap((T::getRs).andThen(List::stream));
要将其放在一条线上,您可以将其拆分为对 Stream#map
的调用,然后是 Stream#flatMap
:
List<T> ts = ...;
ts.stream().map(T::getRs).flatMap(List::stream);
您的 one-line 解决方案的问题是,编译器需要一个目标类型来调用 andThen
。如果您将第一个方法引用转换为 Function
,它工作正常:
ts.stream().flatMap(((Function<T, List<R>>) T::getRs).andThen(List::stream));
首选方法是将这两个拆分为 map
和 flatMap
或使用 lambda 表达式,因为它更具可读性。
编译没有错误:
Function<T, List<R>> f = T::getRs;
Function<List<R>, Stream<R>> g = List::stream;
Function<T, Stream<R>> h = f.andThen(g);
List<T> ts = ...;
ts.stream().flatMap(h);
但这会产生错误:
List<T> ts = ...;
ts.stream().flatMap(T::getRs.andThen(List::stream));
错误是:
error: method reference not expected here
.flatMap(T::getRs.andThen((List::stream)))
^
error: invalid method reference
.flatMap(T::getRs.andThen((List::stream)))
^
non-static method stream() cannot be referenced from a static context
where E is a type-variable:
E extends Object declared in interface Collection
我原以为这两种方法是等价的。我缺少一些语法吗?也许在某处分组?如果可能的话,我更愿意采用后一种 "one-line" 方法。
这不是方法参考的正确语法;好像你正在尝试调用这样的东西(注意括号,即使它仍然不正确):
List<T> ts = ...;
ts.stream().flatMap((T::getRs).andThen(List::stream));
要将其放在一条线上,您可以将其拆分为对 Stream#map
的调用,然后是 Stream#flatMap
:
List<T> ts = ...;
ts.stream().map(T::getRs).flatMap(List::stream);
您的 one-line 解决方案的问题是,编译器需要一个目标类型来调用 andThen
。如果您将第一个方法引用转换为 Function
,它工作正常:
ts.stream().flatMap(((Function<T, List<R>>) T::getRs).andThen(List::stream));
首选方法是将这两个拆分为 map
和 flatMap
或使用 lambda 表达式,因为它更具可读性。