Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java Lamda question

Options
  • 21-09-2016 1:41pm
    #1
    Closed Accounts Posts: 6,075 ✭✭✭


    Can someone please explain how, in FindMatchingAnimals, a -> a.canHop() maps to CheckTrait trait in method print()?

    I know that a -> a.canHop() is the same as
    anonymous_method(Animal a) {
    return a.canHop();
    }
    

    but how does the compiler related the animal class to the CheckTrait interface? I know the JVM uses the 'context', but I'm not sure I get that? How does this work?
    CheckTrait ct = a -> a.canHop()
    
    public interface CheckTrait {
    
        public boolean test(Animal a);
    }
    
    public class Animal {
    
        private String species;
        private boolean canHop;
        private boolean canSwim;
        public Animal(String speciesName, boolean hopper, boolean swimmer) {
            species = speciesName;
            canHop = hopper;
            canSwim = swimmer;
        }
        public boolean canHop() {
            return canHop;
        }
    
        public boolean canSwim() { return canSwim; }
        public String toString() { return species; }
    }
    
    public class FindMatchingAnimals {
    
        private static void print(Animal animal, CheckTrait trait) {
            if (trait.test(animal))   {
                System.out.println(animal);
            }
        }
    
        public static void main(String[] args) {
    
            print(new Animal("fish", false, true), a -> a.canHop());
            print(new Animal("kangaroo", true, false), a -> a.canHop());
        }
    }
    


Comments

  • Registered Users Posts: 243 ✭✭Decos


    Java knows how to map the lambda to the CheckTrait interface by looking at the print method in your FindMatchingAnimalsClass.

    In the FindMatchingAnimals class in the main method you have:
    print(new Animal("fish", false, true), a -> a.canHop());
    

    You are calling the print method and passing a lambda as the second parameter. If you look above at the method signature for the print method you see that it normally expects a CheckTrait as its second parameter. Java sees this and knows then to try and map your lambda to the CheckTrait interface. The CheckTrait interface's method takes an Animal as it's parameter so that means the lambda parameter has to be an Animal.


Advertisement