隐式转换功能接口 [英] Implicit cast of functional interface
问题描述
我的代码:
import java.util.stream.Stream;
@FunctionalInterface
interface StringChanger {
String change(String o);
public class A {
public static void main(String [] args){
Stream.of(hello,world )
.map(new StringChanger(){
@Override
public String change(String o){
return o.trim();
}
})
.forEach(System.out :: println);
$ b 为什么演员不工作?
我得到这个异常:
线程mainjava中的异常。 lang.Error:未解决的编译问题:
类型为Stream< String>的方法映射(Function< ;? super String,?extends R>)不适用于A.main(A.java:13)
的参数(修整器)
map
方法并不期望 StringChanger $ c $ c>执行。它需要一个函数
实现。
你可以做的是创建一个你的 StringChanger
接口,并将实现的方法引用传递给 map
:
<$ p $ (){code $> StringChanger sc = new StringChanger(){
@Override
public String change(String o){
return o.trim();
}
};
Stream.of(hello,world)
.map(sc :: change)
.forEach(System.out :: println);
编辑:
您可以为源函数接口的方法指定一个方法引用:
MyConsumer i3 = i :: accept;
IntConsumer i4 = i2 :: doSomething;
I want to implicitly cast my own interface implementation to a Java8 function.
My code:
import java.util.stream.Stream;
@FunctionalInterface
interface StringChanger {
String change(String o);
}
public class A {
public static void main(String[] args) {
Stream.of("hello", "world")
.map(new StringChanger() {
@Override
public String change(String o) {
return o.trim();
}
})
.forEach(System.out::println);
}
}
Why does the cast not work?
I'm getting this exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method map(Function<? super String,? extends R>) in the type Stream<String> is not applicable for the arguments (Trimmer)
at A.main(A.java:13)
Well, the map
method doesn't expect a StringChanger
implementation. It expects a Function
implementation.
What you can do is create an implementation of your StringChanger
interface, and pass a method reference of your implementation to map
:
StringChanger sc = new StringChanger() {
@Override
public String change(String o) {
return o.trim();
}
};
Stream.of("hello", "world")
.map(sc::change)
.forEach(System.out::println);
EDIT:
In order to assign an implementation of one functional interface to a different functional interface reference, you can assign a method reference of the source functional interface's method :
MyConsumer i3 = i::accept;
IntConsumer i4 = i2::doSomething;
这篇关于隐式转换功能接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!