This question already has an answer here:
I have the following method invocation, in which I am passing a lambda expression. Is a class being instantiated implicitly here?
printStudents(
roster,
(Student s) -> s.getGender() == Student.Sex.MALE
&& s.getAge() >= 18
&& s.getAge() <= 25
);
Method signature:
printStudents(List<Student> roster, CheckStudent checkstudet)
interface CheckStudent {
boolean test(Student s);
}
Edit
Some of you suggested me to refactor the code, but the same question arises.
CheckStudent checkStudent = (Student s) -> s.getGender() == Student.Sex.MALE && s.getAge() >= 18 && s.getAge() <= 25;
Is a class (I am not referring to class Student
) being instantiated on the right side of the assignment?
The value of a lambda expression is a reference to an instance of a class. So, in practical terms, yes, an instance of a class is being created. See what the docs say:
However, there is more to that than we can "see". There are many optimizations running under the hood. Depending on certain factors, a previously created object can, for example, be used again. This means that a new object need not be allocated on every evaluation of a lambda expression. Let's take a look at the docs:
As you might have noticed, this is a complex topic. For a deeper understanding, take a look at the The Java® Language Specification, chapter “15.27.4. Run-time Evaluation of Lambda Expressions”.