bryan.blackbee
bryan.blackbee

Reputation: 1954

Java optional class method cannot be resolved

Given a class Student and its associated method getGrade

class Student{
    public int getGrade(int age){
        return age - 6;
    }
}

When I use the Optional class and call the function getGrade, it resulted in a compilation error with invalid method reference.

import java.util.Optional;
public class Classroom {
    public static void main(String[] args) {

        Student s = new Student();
        Optional<Student> optStu = Optional.ofNullable(s);
        System.out.println(optStu.map(optStu::getGrade));
    }
}

What do I need to change in the sout to print the age of the student?

Upvotes: 2

Views: 9130

Answers (1)

Jai
Jai

Reputation: 8363

optStu.ifPresent(student -> System.out.println(student.getGrade()));

or

optStu.map(Student::getGrade).ifPresent(System.out::println);

Edit

My bad, I didn't notice getGrade() has a parameter.

In short, there is no way to use a lambda expression using :: operator when getGrade() requires a parameter. You can only use the first method:

optStu.ifPresent(student -> System.out.println(student.getGrade(100)));

Upvotes: 4

Related Questions