Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Java Lamda question

  • 21-09-2016 01: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, Registered Users 2 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