Hello,
I find it weird that there is no method for converting an empty String(CharSequence) to null by default in the std.
value?.let {
if (it.isEmpty()) null
else it
}
There should be an extension to do this using something like:
value?.nullIfEmpty()
There’s an extension ifEmpty
, where you can pass a value to be used instead of an empty string:
fun main() {
//sampleStart
val value: String? = ""
value?.ifEmpty { null }
//sampleEnd
.let(::println)
}
2 Likes
kyay10
3
Additionally, you could also do a value.takeUnless { it.isEmpty() }
ifEmpty seems to be the best way to do this, I thought it might be a good inline extension as it is used so much
1 Like