[英]Lambdas in FunctionalInterfaces in Java
I am trying to make use of lambdas in Java
but can't understand how it works at all. 我试图在Java
使用lambdas,但无法理解它是如何工作的。 I created @FunctionalInterface
like this: 我创建了@FunctionalInterface
如下所示:
@FunctionalInterface
public interface MyFunctionalInterface {
String getString(String s);
}
now in my code I use the lambda
as here: 现在在我的代码中我使用lambda
如下:
MyFunctionalInterface function = (f) -> {
Date d = new Date();
return d.toString() + " " + person.name + " used fnc str";
};
Next, I want to make use of my function
passing it into the constructor of another class and use it like this: 接下来,我想利用我的function
将它传递到另一个类的构造函数中,并像这样使用它:
public SampleClass(MyFunctionalInterface function) {
String tmp = "The person info: %s";
this.result = String.format(tmp, function.getString(String.valueOf(function)));
}
Why I need to use it the valueOf()
here? 为什么我需要在这里使用valueOf()
? I thought that thanks for this I could use just function.getString()
? 我想,谢谢你我只能使用function.getString()
?
Output: Tue Sep 19 11:04:48 CEST 2017 John used fnc str
输出: Tue Sep 19 11:04:48 CEST 2017 John used fnc str
Your getString
method requires a String
argument, so you can't call it without any argument. 你的getString
方法需要一个String
参数,所以你不能在没有任何参数的情况下调用它。
That said, your lambda expression ignores that String
argument and instead takes data from some person
variable (which you didn't show where you declare it). 也就是说,你的lambda表达式忽略了String
参数,而是从某个person
变量中获取数据(你没有显示你声明它的位置)。
Perhaps your functional interface should take a Person
argument instead: 也许你的功能界面应该采用Person
参数:
@FunctionalInterface
public interface MyFunctionalInterface {
String getString(Person p);
}
MyFunctionalInterface function = p -> {
Date d = new Date();
return d.toString() + " " + p.name + " used fnc str";
};
public SampleClass(MyFunctionalInterface function, Person person) {
String tmp = "The person info: %s";
this.result = String.format(tmp, function.getString(person));
}
Alternately, you can remove the argument from your functional interface's method: 或者,您可以从功能接口的方法中删除参数:
@FunctionalInterface
public interface MyFunctionalInterface {
String getString();
}
MyFunctionalInterface function = () -> {
Date d = new Date();
return d.toString() + " " + person.name + " used fnc str";
};
public SampleClass(MyFunctionalInterface function) {
String tmp = "The person info: %s";
this.result = String.format(tmp, function.getString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.