Min*_*aze 5 java lambda function java-8
我正在玩Java实用程序功能.我有以下代码:
public class Checker<T>{
private T value;
private Function<T, T> callback;
private Checker(T value) {
this.value = value;
}
public static Checker when(String o) {
return new Checker<String>(o);
}
public static Checker when(int o) {
return new Checker<Integer>(o);
}
public Checker then(Function<T, T> callback) {
this.callback = callback;
return this;
}
public void execute() {
if (this.value instanceof String) {
this.callback.apply("123");
}
if (this.value instanceof Integer) {
this.callback.apply(123);
}
}
Checker.when("123").then(str -> {
return "";
}).execute();
Checker.when(123).then(str -> {
return "";
}).execute();
Run Code Online (Sandbox Code Playgroud)
现在我在这里得到一个错误,this.callback.apply("123")因为它需要T并且无法将其转换为String.
是否可以使用通用返回类型Function<T,T>?我可以发送T,但随后它收到Object我的lambda,但我想要String或Integer.
我在Checker课堂上做了一些改变,这对我来说很有意义.我删除了所有原始类型,我使用了value成员execute.我添加了一个返回类型execute,以便能够打印其结果.
class Checker<T>{
private T value;
private Function<T, T> callback;
private Checker(T value) {
this.value = value;
}
public static Checker<String> when(String o) {
return new Checker<>(o);
}
public static Checker<Integer> when(int o) {
return new Checker<>(o);
}
public Checker<T> then(Function<T, T> callback) {
this.callback = callback;
return this;
}
public T execute() {
return this.callback.apply(value);
}
public static void main (String[] args) {
Checker.when("123").then(str -> {
return "." + str + ".";
}).execute();
Checker.when(123).then(i -> {
return i + 100;
}).execute();
}
}
Run Code Online (Sandbox Code Playgroud)
现在当你检查你的课时:
System.out.println (Checker.when("123").then(str -> "." + str + ".").execute());
System.out.println (Checker.when(123).then(i -> i + 100).execute());
Run Code Online (Sandbox Code Playgroud)
你得到:
.123.
223
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
365 次 |
| 最近记录: |