我有以下代码:
public class LambdaTest1 {
public static void method1(Predicate<Integer> predicate){
System.out.println("Inside Predicate");
}
public static void method1(Function<Integer,String> function){
System.out.println("Inside Function");
}
public static void main(String[] args) {
method1((i) -> "Test");
}
}
Run Code Online (Sandbox Code Playgroud)
这给我一个错误信息
"方法method1(谓词)对于LambdaTest1类型是不明确的".
我可以看到,对于Function和Consumer功能接口,输入参数是Integer.但对于Function,返回类型是String.
因为我的lambda调用具有返回值"Text" - 这应该调用我的Function函数接口而不是抛出此错误.
任何人都可以解释这种行为背后的原因吗?
另一个例子:
public class LambdaTest1 {
public static void method1(Consumer<Integer> consumer){
System.out.println("Inside Consumer");
}
public static void method1(Predicate<Integer> predicate){
System.out.println("Inside Predicate");
}
public static void main(String[] args) {
List<Integer> lst …Run Code Online (Sandbox Code Playgroud) 假设我们有以下案例类:
case class CasePerson(firstName: String)
Run Code Online (Sandbox Code Playgroud)
我们还为它定义了一个伴侣对象:
object CasePerson {
def apply() = new CasePerson( "XYZ" )
}
Run Code Online (Sandbox Code Playgroud)
请注意,在上面的示例中,我使用apply方法显式定义了伴随对象,而没有定义默认的apply方法:
// This "default" apply has the same argument as the primary constructor of the case class
def apply(firstName : String) = new CasePerson(firstName)
Run Code Online (Sandbox Code Playgroud)
问:那么Scala在哪里获得"默认"适用?我在这里明确定义了伴随对象,没有默认的apply,编译器仍然知道如何执行:
val casePerson = CasePerson("PQR")
Run Code Online (Sandbox Code Playgroud)
这是如何运作的?