isNotEmpty() method returns null on Nullable string object

I guess you understand that a?.isNotEmpty can return either null if a is null or the result of a.isNotEmpty(). If not you should take another look at the documentation under Safe Calls.
So when you use !! it will throw a NPE if a is null.

If itself can not handle nullable parameters (I’m not sure where this is explained exactly, I think it is somewhere in the documentation but I can not find it right now). That’s why you have to use the comparison.

null == true => false
false == true => false
true == true => true

You could also create your own utility


fun String?.isNotNullNorEmpty() =
	this?.isNotEmpty() == true
// or
fun String?.isNotNullNorEmpty() =
	this?.isNotEmpty() ?: false

Btw, once you understand safe calls properly I would prefer my second utility as it is easier to understand IMO, considering how safe calls work. But I guess that is preference and not universally right.

1 Like