Mike Spencer
Mike Spencer

Reputation: 13

Returning an object of same return type gives a syntax error

I have two functions. They are as follows,

public Post findById(Long id){
    for (Post thePost : ALL_POSTS) {
        if(thePost.getId()==id){
            return thePost;
        }
    }
    return null;
}


public Post findById_Two(Long id) {
    ALL_POSTS.forEach((thePost) -> {
        if(thePost.getId()==id){
            System.out.println(thePost.getId()==id);
            return thePost;
        }
    });
    return null;
}

As you can see, both functions have a return Type of class Post and returns an object of the same class after a simple check. The first function works fine without any errors while the second function gives me an Unexpected return value error while trying to return thePost.

Can you please let me know what is causing this error and where did I go wrong?

Upvotes: 1

Views: 235

Answers (1)

The problem is that using return from inside a lambda expression returns from the lambda. Your forEach expects a Consumer<Post>, which is normally void. It's okay to provide a lambda that does return a value where void is expected (the value is just ignored), but you are returning a value only where you have a match—and then you'd proceed to return null unconditionally.

If you're going to use lambdas, use lambda style:

public Post findById_streams(Long id) {
  return ALL_POSTS.stream()
    .filter(post -> id.equals(post.getId()))
    .findFirst()
    .orElse(null);
}

(Note also that you have a bug in comparing Long by ==; the code above handles that.)

Upvotes: 2

Related Questions