Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 */ }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement