为什么这个函数式接口是有效的

huangapple go评论82阅读模式
英文:

Why this functional interface is valid

问题

我找到了一个使用 Java Predicate 函数式接口的示例:

BiPredicate<String, String> b1 = String::startsWith;
BiPredicate<String, String> b2 =
            (string, prefix) -> string.startsWith(prefix);
System.out.println(b1.test("chicken", "chick"));
System.out.println(b2.test("chicken", "chick"));

我理解 b2 的工作方式 - 很清楚。
编译器如何理解如何使用 b1 方法?方法 boolean startWith(String str) 只有一个参数。String 类并没有 boolean startWith(String srt1, String srt2) 方法。

英文:

I have found an example with java predicate functional interface:

BiPredicate&lt;String, String&gt; b1 = String::startsWith;
BiPredicate&lt;String, String&gt; b2 =
            (string, prefix) -&gt; string.startsWith(prefix);
System.out.println(b1.test(&quot;chicken&quot;, &quot;chick&quot;));
System.out.println(b2.test(&quot;chicken&quot;, &quot;chick&quot;));

I understand how b2 works - it's clear.
How does the compiler understand how to use the b1 method? Method boolean startWith(String str) has only one parameter. String class doesn't have
boolean startWith(String srt1, String srt2) method.

答案1

得分: 5

> 方法 startWith(String str) 只有一个参数。

实际上,String.startsWith 方法有一个隐含的 this 参数,因为你是在一个 对象实例 上调用它的。因此,它符合一个具有两个 String 参数的函数接口。

正如 Giorgi 所提到的,你应该查阅关于 方法引用 的文档,因为这种语法涉及更多内容,以及在::之前的名称是指对象名还是类名时的工作方式。

简要地说,有四种情况。假设一个具有两个参数 ab 的方法调用的函数接口:

  1. Class::staticMethod

    这等同于 (a, b) -&gt; Class.staticMethod(a, b)

  2. object::method

    这等同于 (a, b) -&gt; object.method(a, b)

  3. Class::method

    这等同于 (a, b) -&gt; a.method(b)

  4. Class::new

    这等同于 (a, b) -&gt; new Class(a, b)

英文:

> Method startWith(String str) has only one parameter.

Actually String.startsWith has an implicit this parameter because you’re calling it on an object instance. Thus it conforms to a functional interface with two String parameters.

As mentioned by Giorgi, you should consult the documentation on method references, since there’s a lot more to this syntax, and the way it works when the name before :: refers to an object versus a class name.

Briefly, there are four cases. Assuming a functional interface for a method call with two parameters a and b:

  1. Class::staticMethod

    This is equivalent to (a, b) -&gt; Class.staticMethod(a, b).

  2. object::method

    This is equivalent to (a, b) -&gt; object.method(a, b).

  3. Class::method

    This is equivalent to (a, b) -&gt; a.method(b).

  4. Class::new

    This is equivalent to (a, b) -&gt; new Class(a, b).

huangapple
  • 本文由 发表于 2020年10月8日 18:41:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64260815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定