I just started looking at Java 8 Lambda feature. I wrote this code in Java 7 and tried to execute it's equivalent in lamdas. Notice that the last line produces a Compilation error because the overloaded function is ambiguous. I understand the reason. How can I resolve this ambiguity with 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
}
}