下面的代码
Supplier<String> newString = String::new;
System.out.println(newString.get());
// prints an empty string (nothing) to the console and then a newline character
以及供应商获取方法的定义
T get()
get方法应该返回T,但是构造函数没有返回类型,那么为什么String::new可以分配给Supplier
最佳答案
我认为两个例子可以解释它,首先你想要的是一个提供有意义的字符串来打印的供应商。就像,
Supplier<String> newString = () -> "test";
System.out.println(newString.get());
您提供的是一个空字符串。就像,
System.out.println(new String());
生成一个空字符串是完全有效的,即使结果偏离了您的预期。
额外第三个示例,详细说明第一个示例,在 lambda 表达式中,您实际上正在实现 single abstract method从功能接口(interface) - 特别是 Supplier<T>
。就像,
Supplier<String> newString = new Supplier<String>() {
@Override
public String get() {
return "test"; // originally return new String()
}
};
System.out.println(newString.get());
关于java - 供构造函数引用的供应商接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60138689/