Guest User

Untitled

a guest
Nov 19th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. /**
  2. Kotlin doesn't seem to have a simple way to convert from a T? to an Optional<T>.
  3. If you are forced to work with Map<T> then you may experience this problem.
  4.  
  5. The below extension function will add a method to all nullable types allowing a nullable to be coerced to an Optional
  6. and a null to be coerced to an Optional.empty
  7.  
  8. (e.g.):
  9. **/
  10. fun exampleUsageToOptional(){
  11. val nullableMap:Map<String, String> = mapOf("foo" to "bar")
  12. val optional = nullableMap.get("foo").toOptional()
  13. val empty = nullableMap.get("somethingelse").toOptional()
  14.  
  15. optional.ifPresent{println("will print")}
  16. empty.ifPresent{println("won't print")}
  17. }
  18. /**
  19. toOptional extension function
  20. **/
  21. fun <T> T?.toOptional(): Optional<T> {
  22. return when (this) {
  23. null -> Optional.empty()
  24. else -> Optional.of(this)
  25. }
  26. }
  27. /**
  28. The additional helper will allow you to take an Optional<T> directly from a Map<K, T>
  29. **/
  30. fun exampleUsagegetOptional(){
  31. val nullableMap:Map<String, String> = mapOf("foo" to "bar")
  32.  
  33. nullableMap.getOptional("foo").ifPresent{println("will print")}
  34. nullableMap.getOptional("somethingelse").ifPresent{println("won't print")}
  35. }
  36. /**
  37. getOptional extension function
  38. **/
  39. fun <K, V> Map<K,V>.getOptional(key:K): Optional<V> {
  40. return this.get(key).toOptional()
  41. }
Add Comment
Please, Sign In to add comment