Kotlin CharSequence.nullIfEmpty()


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:


There’s an extension ifEmpty, where you can pass a value to be used instead of an empty string:

fun main() {
val value: String? = ""
value?.ifEmpty { null }

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