Sam
Sam

Reputation: 566

Lambda exercise

I'm doing some Java OCA test simulations. I don't understand the answer for this exercise:

interface Climb {
   boolean isTooHigh(int height, int limit);
}

public class Lambdas {
    public static void main(String[] args) {
        check((h,l) -> l, 5);
    }

    private static void check(Climb climb, int height) {
        if (climb.isTooHigh(height, 10))
            System.out.println("Too");
        else
            System.out.println("ok");
    }
}

I don't understand if l is "l" or "1" because the spelling is a little incomprehensible. I also did not understand the logic of this exercise.

Can you tell me what is necessary to correct form: l or 1? Can you explain me this exercise?

Thanks a lot!

Upvotes: 0

Views: 114

Answers (1)

Soleil
Soleil

Reputation: 7287

Here is what is happening:

(h,l) -> l is a lambda that takes h and l and returns l. According to interface Climb, h and l as arguments are int and the returned l should be bool; there seems to be an implicit type conversion.

Hence the line check((h,l) -> l, 5); is fine and take arguments of the right type (Climb , int).

(h,l) -> l is just doing: "let's forget about h, and if l != 0, return true else if l == 0 return false".

PS: if it was 1, the answer would be constantly true

Corrected version

interface Climb {
    boolean isTooHigh(int height, int limit);
}
public class Main {
    public static void main(String[] args) {
        check((h,l) -> h>l, 5);
    }
    private static void check(Climb climb, int height) {
            System.out.println(climb.isTooHigh(height, 10) ? "Too":"ok" );
    }
}

Upvotes: 1

Related Questions