In Java, we've always been reminded to use myString.isEmpty()
to check whether a String is empty. In Kotlin however, I find that you can use either myString == ""
or myString.isEmpty()
or even myString.isBlank()
.
Are there any guidelines/recommendations on this? Or is it simply "anything that rocks your boat"?
Thanks in advance for feeding my curiosity. :D
Java String isEmpty() Method The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.
Returns true if this string is empty or consists solely of whitespace characters.
isEmpty(): Boolean. Returns true if this char sequence is empty (contains no characters).
Don't use myString == ""
, in java this would be myString.equals("")
which also isn't recommended.
isBlank
is not the same as isEmpty
and it really depends on your use-case.
isBlank
checks that a char sequence has a 0 length or that all indices are white space. isEmpty
only checks that the char sequence length is 0.
/** * Returns `true` if this string is empty or consists solely of whitespace characters. */ public fun CharSequence.isBlank(): Boolean = length == 0 || indices.all { this[it].isWhitespace() } /** * Returns `true` if this char sequence is empty (contains no characters). */ @kotlin.internal.InlineOnly public inline fun CharSequence.isEmpty(): Boolean = length == 0
For String?
(nullable String) datatype, I use .isNullOrBlank()
For String
, I use .isBlank()
Why? Because most of the time, I do not want to allow Strings with whitespace (and .isBlank()
checks whitespace as well as empty String). If you don't care about whitespace, use .isNullorEmpty()
and .isEmpty()
for String?
and String
, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With