How can I pull data out of an Option for independent use?

if let Some(origin) = resp.get(“origin”) { // use origin } If you can guarantee that it’s impossible for the value to be None, then you can use: let origin = resp.get(“origin”).unwrap(); Or: let origin = resp.get(“origin”).expect(“This shouldn’t be possible!”); And, since your function returns a Result: let origin = resp.get(“origin”).ok_or(“This shouldn’t be possible!”)?; Or with … Read more

Proper usage of Optional.ifPresent()

Optional<User>.ifPresent() takes a Consumer<? super User> as argument. You’re passing it an expression whose type is void. So that doesn’t compile. A Consumer is intended to be implemented as a lambda expression: Optional<User> user = … user.ifPresent(theUser -> doSomethingWithUser(theUser)); Or even simpler, using a method reference: Optional<User> user = … user.ifPresent(this::doSomethingWithUser); This is basically the … Read more

Downcasting optionals in Swift: as? Type, or as! Type?

The practical difference is this: var optionalString = dict[“SomeKey”] as? String optionalString will be a variable of type String?. If the underlying type is something other than a String this will harmlessly just assign nil to the optional. var optionalString = dict[“SomeKey”] as! String? This says, I know this thing is a String?. This too … Read more

Java 8 optional: ifPresent return object orElseThrow exception

Actually what you are searching is: Optional.map. Your code would then look like: object.map(o -> “result” /* or your function */) .orElseThrow(MyCustomException::new); I would rather omit passing the Optional if you can. In the end you gain nothing using an Optional here. A slightly other variant: public String getString(Object yourObject) { if (Objects.isNull(yourObject)) { // … Read more