Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a parameter to a function only if not null

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?

like image 454
Old Man of Aran Avatar asked Jun 30 '26 03:06

Old Man of Aran


1 Answers

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)
like image 80
Todd Avatar answered Jul 01 '26 19:07

Todd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!