/**
* 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
3 回答
不要使用
myString == ""
,在java中这将是myString.equals("")
,也不推荐使用 .isBlank
与isEmpty
不同,它实际上取决于您的用例 .isBlank
检查char序列的长度是0还是所有索引都是空格 .isEmpty
仅检查char序列长度是否为0 .对于String? (nullable String)数据类型,我用
.isNullOrBlank()
对于String,我使用
.isBlank()
为什么?因为大多数时候,我不想允许带有空格的字符串(并且
.isBlank()
检查空格以及空字符串) . 如果您不关心空格,请使用.isNullorEmpty()
和.isEmpty()
作为字符串?和String,分别 .如果要测试String是否与空字符串
""
完全相等,请使用isEmpty
.如果要测试String为空或仅包含空格(
""
," "
),请使用isBlank
.避免使用
== ""
.