Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. fun f(vararg strings: String, block: () -> Unit): String {
  2. // this implementation makes no sense, but the signature it's based on does.
  3. block()
  4. return if (strings.isEmpty()) {
  5. "hello"
  6. } else {
  7. strings.reduce{ a, b -> a + b }
  8. }
  9. }
  10.  
  11. val a: String? = "hi"
  12.  
  13. // we have function that takes a vararg and block, and a nullable val.
  14.  
  15. // option 1
  16. if (a != null) {
  17. f(a){ /* block */ }
  18. } else {
  19. f { /* same block again */}
  20. }
  21.  
  22. // option 2
  23. a?.let{
  24. f(a) {/* block */}
  25. } ?: f { /* same block again :( */}
  26.  
  27. // option 3 spread array
  28. val aOrEmpty = a?.let{arrayOf(it)} ?: emptyArray()
  29. f(*aOrEmpty) { /* block only once */ }
  30.  
  31. // option 4 wrapper function
  32. fun fHelper(string: String?, block: () -> Unit): String = if (string != null) f(string){block()} else f { block() }
  33. fHelper(a) { /* block */ }
  34.  
  35. // option 5
  36. f(*listOfNotNull(a).toTypedArray()) { /*block*/ }
  37.  
  38. /* Why not, kotlinc?
  39. // non-option 6
  40. f(*a) { /* block */ }
  41. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement