Page 1 of 1

About Question enthuware.ocpjp.v8.2.1784 :

Posted: Sun Sep 01, 2019 9:54 am
by tylrdr

Code: Select all

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Common {

    public static void main(String[] args) {

        List<Integer> values = Arrays.asList(2, 4, 6, 9);
        Predicate<Integer> check = (Integer i) -> {
            System.out.println("Checking");
            return i == 4;
        };
        Predicate<Integer> even = (Integer i) -> i % 2 == 0; //Compiles
//        Predicate even =  i -> ((Integer)i) % 2 == 0; //Compiles
//        Predicate even = (Object i) -> ((Integer)i) % 2 == 0; //Compiles

//        Predicate even = (Integer i) -> i % 2 == 0; //Doesn't compile: expected Object but found Integer
//        Predicate even = (Integer i) -> ((Integer)i) % 2 == 0; //Doesn't compile: expected Object but found Integer
//        Predicate even = (Object i) -> ((Object)i) % 2 == 0; //Doesn't compile: Operator '%' can't be applied to java.lang.Object
//        Predicate even = (Object i) -> i % 2 == 0; //Doesn't compile: Operator '%' can't be applied to java.lang.Object


        values.stream().filter(check).filter(even).count(); //Checking Checking Checking Checking
    }
}
I tested a bit and found these examples. Could someone please explain if there is some rules that is useful to remember for this to make sense please?
1) Why does Java expect Object to be the type of lambda variable? Why can't Java figure out the type by itself like it does here:
Predicate even = i -> ((Integer)i) % 2 == 0; //Compiles
2) Why in Java operator '%' can't be applied to java.lang.Object?

Re: About Question enthuware.ocpjp.v8.2.1784 :

Posted: Sun Sep 01, 2019 11:23 pm
by admin
>Why does Java expect Object to be the type of lambda variable?
Java doesn't expect Object to be the type of lambda variable. Type of the lambda depends on the type of function parameter that you are trying to implement. Please do through short article to understand: https://enthuware.com/lambda-for-ocajp

> Why in Java operator '%' can't be applied to java.lang.Object?
Well, you know what % does, right? It divides one number by another and return the remainder. It is a mathematical operation. How will you divide an object?