In Java, we've always been reminded to use myString.isEmpty() to check whether a String is empty. In Kotlin however, I find that you can use either myString == "" or myString.isEmpty() or even myString.isBlank().

对此有什么指导/建议吗?或者仅仅是"任何能震撼你船的事情"?

Thanks in advance for feeding my curiosity. :D

推荐答案

不要使用myString == "",在java中,这将是myString.equals(""),这也不推荐使用.

isBlankisEmpty不一样,这取决于你的用例.

isBlank checks that a char sequence has a 0 length or that all indices are white space. isEmpty only checks that the char sequence length 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

Kotlin相关问答推荐

用浮点数或十进制数给出错误答案的阶乘计算

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

如何使用multiset与JOOQ获取关联的记录列表?

为什么 Kotlin main 函数需要 @JVMStatic 注解?

判断 Kotlin 变量是否为函数

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

Jetpack Compose 中的连续重组

如何在 Kotlin 中不受约束?

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

使用 Discord4j 交叉发布 Discord 消息

为什么 KFunction2 在 Kotlin 中不是可表示类型?

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

runBlocking 中的 deferred.await() 抛出的异常即使在被捕获后也被视为未处理

@InlineOnly 注释是什么意思?

在Kotlin中不带类直接引用枚举实例

Kotlin 接口属性:只需要公共 getter 而没有公共 setter

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Kotlin协程无法处理异常

使用 java lambda 调用 kotlin 函数时,Kotlin 无法访问 kotlin.jvm.functions.Function1

在 intelliJ 元素中集成 Kotlinx 协程