检查Kotlin中的字符串是否为空

在Java中,我们总是提醒使用myString.isEmpty()来检查一个字符串是否为空。 但是,在Kotlin中,我发现可以使用myString == ""myString.isEmpty()甚至myString.isBlank()

有没有关于这方面的指导方针/建议? 还是仅仅是“任何事情都会让你的船摇晃”?

提前感谢喂养我的好奇心。 :d

不要使用myString == "" ,在java中这将是myString.equals("") ,这也不建议。

isBlankisEmpty不一样,它取决于你的用例。

isBlank检查char序列长度是0还是所有索引都是空格。 isEmpty仅检查char序列长度是否为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 

对于字符串? (可空字符串)数据类型,我使用.isNullOrBlank()

对于字符串,我使用.isBlank()

为什么? 因为大多数时候,我不希望允许带空格的字符串(和.isBlank()检查空字符串以及空字符串)。 如果您不关心空格,请使用.isNullorEmpty().isEmpty()作为String? 和String。

如果要测试字符串是否与空字符串""完全相同,请使用isEmpty

当你想测试一个字符串是空的还是只包含空白( """ " )时,使用isBlank

避免使用== ""