Checking for empty lines in Kotlin

In Java, we have always been reminded to use myString.isEmpty() to check if a string is empty. However, in Kotlin, I find that you can use either myString == "" , or myString.isEmpty() or even myString.isBlank() .

Are there any recommendations / recommendations on this? Or is it just "everything that pumps your boat"?

Thanks in advance for expressing my curiosity .: D

+27
source share
5 answers

Do not use myString == "" , in java it will be myString.equals("") , which is also not recommended.

isBlank not the same as isEmpty , and it really depends on your use case.

isBlank checks that the char sequence has a length of 0 or that all indexes are spaces. isEmpty only checks that the length of the char sequence 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 
+34
source

For the string? (nullable String), I am using .isNullOrBlank()

For String, I use .isBlank()

Why? Since most of the time I do not want to allow lines with spaces (and .isBlank() checks for spaces as well as an empty line). If you don't need spaces, use .isNullorEmpty() and .isEmpty() for String? and String, respectively.

+16
source

Use isEmpty if you want to check that the string is exactly equal to the empty string "" .

Use isBlank if you want to check that the string is empty or consists only of spaces ( "" , " " ).

Avoid using == "" .

+6
source

You can use isNullOrBlank() to check if a string is null or empty. This method considers empty lines only spaces.

Here is a usage example:

 val s: String? = null println(s.isNullOrBlank()) val s1: String? = "" println(s1.isNullOrBlank()) val s2: String? = " " println(s2.isNullOrBlank()) val s3: String? = " a " println(s3.isNullOrBlank()) 

The result of this snippet:

 true true true false 
0
source

There are two methods in Kotlin. 1. isNullOrBlank () 2. isNullOrEmpty ()

And the difference is

  data = " " // this is a text with blank space println(data.isNullOrBlank()?.toString()) //true println(data.isNullOrEmpty()?.toString()) //false 
0
source

Source: https://habr.com/ru/post/1270245/


All Articles