What is the difference between Optional.flatMap and Optional.map?

Use map if the function returns the object you need or flatMap if the function returns an Optional. For example: public static void main(String[] args) { Optional<String> s = Optional.of(“input”); System.out.println(s.map(Test::getOutput)); System.out.println(s.flatMap(Test::getOutputOpt)); } static String getOutput(String input) { return input == null ? null : “output for ” + input; } static Optional<String> getOutputOpt(String input) … Read more

GC overhead of Optional in Java

We all know that every object allocated in Java adds a weight into future garbage collection cycles,… That sounds like a statement nobody could deny, but let’s look at the actual work of a garbage collector, considering common implementations of modern JVMs and the impact of an allocated object on it, especially objects like Optional … Read more

Swift optional escaping closure parameter

from: swift-users mailing list Basically, @escaping is valid only on closures in function parameter position. The noescape-by-default rule only applies to these closures at function parameter position, otherwise they are escaping. Aggregates, such as enums with associated values (e.g. Optional), tuples, structs, etc., if they have closures, follow the default rules for closures that are … Read more

Chaining Optionals in Java 8

Use a Stream: Stream.of(find1(), find2(), find3()) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); If you need to evaluate the find methods lazily, use supplier functions: Stream.of(this::find1, this::find2, this::find3) .map(Supplier::get) .filter(Optional::isPresent) .map(Optional::get) .findFirst();

Two (or more) optionals in Swift

(Updated for Swift >=3) “Double optionals” can be useful, and the Swift blog entry “Optionals Case Study: valuesForKeys” describes an application. Here is a simplified example: let dict : [String : String?] = [“a” : “foo” , “b” : nil] is a dictionary with optional strings as values. Therefore let val = dict[key] has the … Read more