Returning a value from a method within a lambda expression

前端 未结 2 724
忘了有多久
忘了有多久 2021-01-07 19:10

I\'m trying to figure out how to return a method value from a lambda expression:

public int findMissingNumber(Collection ints) {
    Single<         


        
2条回答
  •  轮回少年
    2021-01-07 19:29

    Is there some type of way to break or force a return for the entire method?

    No. At least, not unless you throw an exception.

    Basically, that's not what forEach is meant for. You could write a method which accepted a function which would return null for "keep going" and non-null for "stop, and make this the result"... but that method isn't forEach.

    The fact that you're using a lambda expression is really incidental here. Imagine you were just calling forEach and passing in some argument - wouldn't it be really weird if that call made your findMissingNumber method return (without an exception), without the findMissingNumber method itself having the return statement?

提交回复
热议问题