I need to pass a nullable parameter to a function that only accepts non nullable objects, but has a default value defined.
Currently I'm using a let:
fun myFun(a:String = "qqq"): Whatever {...}
val myString:String? = getNullableString()
val myFunResult = myString.?let{myFun(it)}?:myFun()
This is verbose and it is no more possible when there's more than an optional parameter. I'd need something like
val myFunResult = myFun(myString?:default)
Is there a pratical way to do this?
If you don't want to repeat the default value outside of the function (I wouldn't) you are going to have to do some kind of conditional check. Personally speaking, I find the let expression hard to read when scanning code, and would probably just go with an if. Keep in mind that in Kotlin, if is an expression:
if(myString == null) myFun() else myFun(myString)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With