Skip to content

Instantly share code, notes, and snippets.

@eddsteel
Last active March 13, 2019 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddsteel/33c657ed0d690c1adac68d437680bfa5 to your computer and use it in GitHub Desktop.
Save eddsteel/33c657ed0d690c1adac68d437680bfa5 to your computer and use it in GitHub Desktop.
nullables and varargs
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