Last active
March 13, 2019 18:52
-
-
Save eddsteel/33c657ed0d690c1adac68d437680bfa5 to your computer and use it in GitHub Desktop.
nullables and varargs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun f(vararg strings: String, block: () -> Unit): String { | |
// this implementation makes no sense, but the signature it's based on does. | |
block() | |
return if (strings.isEmpty()) { | |
"hello" | |
} else { | |
strings.reduce{ a, b -> a + b } | |
} | |
} | |
val a: String? = "hi" | |
// we have function that takes a vararg and block, and a nullable val. | |
// option 1 | |
if (a != null) { | |
f(a){ /* block */ } | |
} else { | |
f { /* same block again */} | |
} | |
// option 2 | |
a?.let{ | |
f(a) {/* block */} | |
} ?: f { /* same block again :( */} | |
// option 3 spread array | |
val aOrEmpty = a?.let{arrayOf(it)} ?: emptyArray() | |
f(*aOrEmpty) { /* block only once */ } | |
// option 4 wrapper function | |
fun fHelper(string: String?, block: () -> Unit): String = if (string != null) f(string){block()} else f { block() } | |
fHelper(a) { /* block */ } | |
// option 5 | |
f(*listOfNotNull(a).toTypedArray()) { /*block*/ } | |
/* Why not, kotlinc? | |
// non-option 6 | |
f(*a) { /* block */ } | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment