gpt4 book ai didi

java - String.concat 用作 BiFunction

转载 作者:搜寻专家 更新时间:2023-11-01 02:38:04 24 4
gpt4 key购买 nike

在尝试使用方法引用时,遇到了可以将 concat 方法用作 BiFunction 的情况,据我所知,BiFunction apply 方法需要 2 个输入参数并产生一个结果。然而,concat 方法接受 1 个输入参数并返回具有该值的连接字符串。

示例代码:

public class Test {
public static void main(String[] args) {
Test t = new Test();
String str1 = "Hello";
String str2 = "Workld";
System.out.println(t.stringManipulator(str1, str2, String::concat));
System.out.println(str1);
System.out.println(str2);
}
private String stringManipulator(String inputStr, String inputStr2, BiFunction<String, String, String> function) {
return function.apply(inputStr, inputStr2);
}
}

输出

HelloWorkld
Hello
Workld

谁能帮我理解这里发生了什么?

最佳答案

String.concat() 方法有两个参数。第一个是(隐式)参数是调用该方法的字符串,第二个是显式参数。

str1.concat(str2)

str1 是隐式参数(在 concat 方法中它可以作为 this 访问),str2是显式参数。

或者,如 Java 语言规范 (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13.3) 中所述

If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is as specified in §15.12.4.3, §15.12.4.4, and §15.12.4.5, where:

  • The invocation mode is derived from the compile-time declaration as specified in §15.12.3.

  • If the compile-time declaration is an instance method, then the target reference is the first formal parameter of the invocation method. Otherwise, there is no target reference.

  • If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.

也就是说,那个

  BiFunction<String, String, String> function = String::concat;
function.apply("abc", "def");

将被执行为

  "abc".concat("def");

关于java - String.concat 用作 BiFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com