Difference between `Optional.orElse()` and `Optional.orElseGet()`

I am trying to understand the difference between the Optional<T>.orElse() and Optional<T>.orElseGet() methods. The description for the orElse() method is “Return the value if present, otherwise return other.” While, the description for the orElseGet() method is “Return the value if present, otherwise invoke other and return the result of that invocation.” The orElseGet() method takes … Read more

Why use Optional.of over Optional.ofNullable?

When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional. String foobar = <value or null>; Optional.of(foobar); // May throw NullPointerException Optional.ofNullable(foobar); // Safe from NullPointerException I understand Optional.ofNullable is the only safe way of using Optional, but why does Optional.of exist at all? … Read more

Are parameters in strings.xml possible? [duplicate]

This question already has answers here: Is it possible to have placeholders in strings.xml for runtime values? (14 answers) Closed 4 years ago. In my Android app I’am going to implement my strings with internationalization. I have a problem with the grammar and the way sentences build in different languages. For example: “5 minutes ago” … Read more

Functional style of Java 8’s Optional.ifPresent and if-not-Present?

In Java 8, I want to do something to an Optional object if it is present, and do another thing if it is not present. if (opt.isPresent()) { System.out.println(“found”); } else { System.out.println(“Not found”); } This is not a ‘functional style’, though. Optional has an ifPresent() method, but I am unable to chain an orElse() … Read more

Why create “Implicitly Unwrapped Optionals”, since that implies you know there’s a value?

Why would you create a “Implicitly Unwrapped Optional” vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create an optional in the first place? For example, why is this: let someString: String! = “this is the string” going to be more useful than: let someString: … Read more

What does an exclamation mark mean in the Swift language?

The Swift Programming Language guide has the following example: class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println(“\(name) is being deinitialized”) } } class Apartment { let number: Int init(number: Int) { self.number = number } var tenant: Person? deinit { println(“Apartment #\(number) is being … Read more