Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between isEmpty and isBlank in kotlin

Tags:

android

kotlin

I want to check the value of a String in my in Android project. I saw two functions to check my String value:

item.isBlank()

and

item.isEmpty()

What is difference between them?

like image 618
Alireza aslami Avatar asked Sep 07 '20 13:09

Alireza aslami


People also ask

What is the difference between isEmpty and isBlank?

isBlank() vs isEmpty() Both methods are used to check for blank or empty strings in java. The difference between both methods is that isEmpty() method returns true if, and only if, string length is 0. isBlank() method only checks for non-whitespace characters. It does not check the string length.

Which is better isEmpty or isBlank?

Practically speaking, you should generally use String. isBlank if you expect potentially whitespace strings (e.g. from user input that may be all whitespace), and String. isEmpty when checking fields from the database, which will never contain a string of just whitespace.

What is difference between StringUtils isEmpty and isBlank?

StringUtils isEmpty() Example in Java. The isEmpty() method doesn't check for whitespace. It will return false if our string is whitespace. We need to use StringUtils isBlank() method to check whitespace.

How do you use Kotlin isEmpty?

To check if string is empty in Kotlin, call isEmpty() method on this string. The method returns a boolean value of true, if the string is empty, or false if the string is not empty.


2 Answers

item.isEmpty() checks only the length of the the string

item.isBlank() checks the length and that all the chars are whitespaces

That means that

  • " ".isEmpty() should returns false
  • " ".isBlank() should returns true

From the doc of isBlank

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

like image 186
Blackbelt Avatar answered Oct 06 '22 08:10

Blackbelt


In future, you can read documentation and see the code from IDE just click Ctrl+B or Command+B. This is written in documantation for isEmpty method:

/**
 * Returns `true` if this char sequence is empty (contains no characters).
 *
 * @sample samples.text.Strings.stringIsEmpty
 */
@kotlin.internal.InlineOnly
public inline fun CharSequence.isEmpty(): Boolean = length == 0

And for isBlank:

 * Returns `true` if this string is empty or consists solely of whitespace characters.
 *
 * @sample samples.text.Strings.stringIsBlank
 */
public actual fun CharSequence.isBlank(): Boolean = length == 0 || indices.all { this[it].isWhitespace() }
like image 6
Andrii Hridin Avatar answered Oct 06 '22 08:10

Andrii Hridin