Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if string is empty in Kotlin

Tags:

kotlin

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

like image 702
Aba Avatar asked Jul 26 '17 20:07

Aba


People also ask

How do I check if a string is empty?

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.

Is blank Kotlin?

Returns true if this string is empty or consists solely of whitespace characters.

What is empty in Kotlin?

isEmpty(): Boolean. Returns true if this char sequence is empty (contains no characters).


2 Answers

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 
like image 123
Charles Durham Avatar answered Oct 16 '22 00:10

Charles Durham


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.

like image 28
Eric Bachhuber Avatar answered Oct 16 '22 01:10

Eric Bachhuber