gpt4 book ai didi

lambda - 重载函数的 Java 8 Lambda 模棱两可

转载 作者:行者123 更新时间:2023-12-01 23:05:02 26 4
gpt4 key购买 nike

我刚开始研究 Java 8 Lambda 功能。我在 Java 7 中编写了这段代码,并尝试在 lamdas 中执行它。请注意,最后一行会产生编译错误,因为重载的函数不明确。我明白原因。如何使用 lambdas 解决这种歧义?

package com.java8.lambdas;

interface Bounceable{
void bounce(double howHigh);
}

interface Fly{
void flies(double howHigh);
}

abstract class Game{
void play(Bounceable b) {}
void play(Fly f) {}
}

class Ball extends Game{
void play(Bounceable b){ b.bounce(10); }
}

class Kite extends Game{
void play(Fly f){ f.flies(1000); }
}

public class LambdaDemo {

public static void main(String[] args) {


System.out.println("======= Java7: ========");
//Ball game
Game bg = new Ball();
bg.play(new Bounceable(){
@Override
public void bounce(double howHigh) {
System.out.println("Ball: Bouncing "+howHigh);
}
});

//Kite game
Game kg = new Kite();
kg.play(new Fly(){
@Override
public void flies(double howHigh) {
System.out.println("Kite: flies "+howHigh);
}
});


System.out.println("======= Java8 Lambdas: ========");

bg.play(x ->System.out.println("lambda: Ball bouncing "+ x)); //Ambiguous of type of Game

}

}

最佳答案

您可以使用类似强制转换的语法来指示正确的类型;

// bg.Play(Bounceable)
bg.play((Bounceable) x -> System.out.println("lambda: Ball bouncing "+ x));

// kg.Play(Fly)
kg.play((Fly) x -> System.out.println("lambda: Ball bouncing "+ x));

您可以找到有关其工作原理的更多信息in this answer .

关于lambda - 重载函数的 Java 8 Lambda 模棱两可,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362047/

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