Is there any nice pattern to set an optional, nullable argument to a non-null default?
I end up doing a lot of something like this, what seems to be quiet ugly because it requires an additional val with a new name and I have to define the default twice.
fun foo(a: String? = "") {
val nonNullA = a ?: ""
// further processing which requires a to be non-null
}
You can very easily avoid writing the default value twice by setting null
to be the parameter’s default value, and write the actual default value in the method body.
As for avoiding a new name… the parameter name can be shadowed in a lambda, so you can do:
fun foo(a: String? = null) =
(a ?: "").let { a ->
// ...
}
This does give you a warning saying that you are shadowing a name. You can suppress it using @Suppress("NAME_SHADOWING")
, since this is exactly what you want to do.