V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ukipoi
V2EX  ›  Java

请教下, Java 里的方法引用。

  •  
  •   ukipoi · Feb 1, 2018 · 2968 views
    This topic created in 3006 days ago, the information mentioned may be changed or developed.

    《 Java 核心技术 卷一》里第六章的 lambda 表达式里,有出现“ System.out::println ”的形式。这个我还能理解。 但是之后的“ Math::pow ”的形式。书里说它等价于“(x,y)->Math.pow(x,y)”,但是“ Math::pow ”的 x 和 y 的参数是那里传递进去的呢?

    4 replies    2018-02-01 21:42:04 +08:00
    JRight
        1
    JRight  
       Feb 1, 2018   ❤️ 1
    这两个参数是回调方法(回调方法( x,y ))里的参数,这里用两个冒号省略掉了回调方法

    如果有误请大家指出
    qinxi
        2
    qinxi  
       Feb 1, 2018
    如果看不明白的话 建议展开写,,然后利用 IDE 的 replace with lambda 转换过去

    不太恰当的例子:
    public static Double pow(Integer a, Integer b) {
    return new BiFunction<Integer, Integer, Double>() {
    @Override
    public Double apply(Integer integer, Integer integer2) {
    return Math.pow(integer, integer2);
    }
    }.apply(a,b);
    }
    ------------------- IDEA 转成下面的样子
    public static Double pow(Integer a, Integer b) {
    return ((BiFunction<Integer, Integer, Double>) (integer, integer2) -> Math.pow(integer, integer2)).apply(a,b);
    }
    --------------- 手动缩写
    public static Double pow(Integer a, Integer b) {
    return ((BiFunction<Integer, Integer, Double>) Math::pow).apply(a,b);
    }
    ---
    要求 参数顺序 类型 一致
    sudoz
        3
    sudoz  
       Feb 1, 2018
    可以理解是 Java8 的语法糖,实际上代码编译后你能看到真正执行的代码
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5371 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 03:50 · PVG 11:50 · LAX 20:50 · JFK 23:50
    ♥ Do have faith in what you're doing.