https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

martmists

07/25/2022, 10:54 AM
Is there a better way to do function calls similar to this?
Copy code
someFunction(  // takes varargs
    *arrayOf(if (condition) "someValue" else null).filterNotNull().toTypedArray(),
)
w

wbertan

07/25/2022, 10:55 AM
Maybe with
listOfNotNull
?
e

ephemient

07/25/2022, 11:08 AM
Copy code
someFunction(
    *if (condition) arrayOf("someValue") else emptyArray()
)
k

Klitos Kyriacou

07/25/2022, 11:12 AM
I like ephemient's solution but some people may find the following simpler-looking and more readable:
Copy code
if (condition)
    someFunction("someValue")
else
    someFunction()
2
a

Alan B

07/25/2022, 1:08 PM
Or extract it out:
Copy code
fun anotherFunction(condition: Boolean) = 
  if (condition)
    arrayOf("someValue")
  else
    emptyArray()
At least then the “condition” is now testable alone, as it would have been buried in the call of another function and therefore obfuscated.
Copy code
someFunction(*anotherFunction(condition))
3 Views