Table of Contents
Kotlin String has methods, isBlank()
and isEmpty()
. I wrote about their difference.
Environment
- Kotlin 1.2.0
Empty
Empty means no-content. isEmpty
is the same as comparing to zero string (value == ""
).
In definition of the method, it calculate String’s length and compares it to zero.
1 2 3 4 5 |
/** * Returns `true` if this char sequence is empty (contains no characters). */ @kotlin.internal.InlineOnly public inline fun CharSequence.isEmpty(): Boolean = length == 0 |
isEmpty
実行例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
% kotlinc Welcome to Kotlin version 1.2.0 (JRE 1.8.0_151-8u151-b12-0ubuntu0.17.04.2-b12) Type :help for help, :quit for quit >>> "test".isEmpty() false >>> "".isEmpty() true >>> null.isEmpty() error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Nothing? null.isEmpty() ^ error: type inference failed: Not enough information to infer parameter T in inline fun <T> Array<out T>.isEmpty(): Boolean Please specify it explicitly. null.isEmpty() ^ |
Blank
Blank means non-filled, not-printed. isBlank
returns true
for invisible characters, also for wide space and CR, LF, and so on.
1 2 3 4 |
/** * 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() } |
Internally, it uses isWhitespace
method.
1 2 3 4 5 |
/** * Determines whether a character is whitespace according to the Unicode standard. * Returns `true` if the character is whitespace. */ public fun Char.isWhitespace(): Boolean = Character.isWhitespace(this) || Character.isSpaceChar(this) |
And Kotlin isWhitespace
method uses Java’s methods, isWhitespace
and isSpaceChar
.
isBlank
実行例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
% kotlinc Welcome to Kotlin version 1.2.0 (JRE 1.8.0_151-8u151-b12-0ubuntu0.17.04.2-b12) Type :help for help, :quit for quit >>> "".isBlank() true >>> "test".isBlank() false >>> "tn r".isBlank() true >>> "tn r".isEmpty() false >>> null.isBlank() error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Nothing? null.isBlank() ^ |
Original Meaning of Empty
and Blank
- Empty
-
Vacent. Describes when there is nothing inside(content). Used in emotional/content-related/idea-related context.
empty bottle, empty bank account
- Blank
-
Nothing to see. Describes facial expression/missing surface content.
blank form, blank sheet, blank piece of paper, blank computer screen
empty and blank are adjective. So emptier, emptiest, blanker, blankest are valid words, but they are not used frequently.
Related Methods
Kotlin prepares methods similar to isEmpty
and isBlank
.
isNotEmpty
isNullOrEmpty
isNotBlank
isNullOrBlank