为什么Stream.of()需要强制转换来接受内联lambda表达式或方法引用?
考虑到这一点:
Function<String,String> f = String::toUpperCase; // works without cast
Stream.of(f); // works without cast
//Stream.of(String::toUpperCase); // Error - target type must be functional interface
Stream.of((Function<String,String>) String
我刚刚在Eclipse上做了一个快速的实验。
public class StackTractTest {
static class Nasty {
public Integer toInt() {
if (1 == 1) throw new RuntimeException();
return 1;
}
}
@Test
public void methodReference() {
Stream.of(new Nasty())
.map(Nasty::toInt)
.findFirst();
}