Doorgaan naar hoofdcontent

Posts

Posts uit 2026 tonen

Optional and continuing

 So, some thing I've bothered myself with. We have a common idiom where we do something like: var result = doSometThing(); if(result == null) {   return handleEmptyCase(); } // continue logic with result     With Optional, that has changed, somewhat... var result = doSometThing(); if(result.isEmpty()) {   return handleEmptyCase(); } var actualResult = result.get(); // continue logic with actualResult   But this is... messy.   We could go functional on it:   return doSomeThing()   .map(result -> doWithActualResult(result))   .orElse( () -> return handleEmptyCase();)   But this isn't it either. We now have the else clause handling our special exit, which is not what we prefer, we prefer to exit early.  So, sometimes an optional is... not as nice...    Something interesting is: https://stackoverflow.com/questions/73248935/using-optionals-is-it-possible-to-return-early-on-ifpresent-without-adding-a     ...