Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Kotlin doesn't seem to have a simple way to convert from a T? to an Optional<T>.
- If you are forced to work with Map<T> then you may experience this problem.
- The below extension function will add a method to all nullable types allowing a nullable to be coerced to an Optional
- and a null to be coerced to an Optional.empty
- (e.g.):
- **/
- fun exampleUsageToOptional(){
- val nullableMap:Map<String, String> = mapOf("foo" to "bar")
- val optional = nullableMap.get("foo").toOptional()
- val empty = nullableMap.get("somethingelse").toOptional()
- optional.ifPresent{println("will print")}
- empty.ifPresent{println("won't print")}
- }
- /**
- toOptional extension function
- **/
- fun <T> T?.toOptional(): Optional<T> {
- return when (this) {
- null -> Optional.empty()
- else -> Optional.of(this)
- }
- }
- /**
- The additional helper will allow you to take an Optional<T> directly from a Map<K, T>
- **/
- fun exampleUsagegetOptional(){
- val nullableMap:Map<String, String> = mapOf("foo" to "bar")
- nullableMap.getOptional("foo").ifPresent{println("will print")}
- nullableMap.getOptional("somethingelse").ifPresent{println("won't print")}
- }
- /**
- getOptional extension function
- **/
- fun <K, V> Map<K,V>.getOptional(key:K): Optional<V> {
- return this.get(key).toOptional()
- }
Add Comment
Please, Sign In to add comment