kotlin 中 isEmpty 和 isBlank 有什么不同

Ali*_*ami 9 android kotlin

我想在我的 android 项目中检查一个字符串的值,所以我看到了我的字符串值的两个函数:

item.isBlank()
Run Code Online (Sandbox Code Playgroud)

item.isEmpty()
Run Code Online (Sandbox Code Playgroud)

它们之间有什么区别?

Bla*_*elt 14

item.isEmpty() 只检查字符串的长度

item.isBlank() 检查长度并且所有字符都是空格

这意味着

  • " ".isEmpty() 应该返回false
  • " ".isBlank() 应该返回真

从文档 isBlank

如果此字符串为空或仅由空白字符组成,则返回 true。


小智 8

将来,您只需单击 Ctrl+B 或 Command+B 即可阅读文档并从 IDE 查看代码。这是在 isEmpty 方法的文档中编写的:

/**
 * 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
Run Code Online (Sandbox Code Playgroud)

对于 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() }
Run Code Online (Sandbox Code Playgroud)