在Java中,我们总是被提醒myString.isEmpty()用来检查String是否为空.在科特林然而,我发现,你可以使用myString == ""或myString.isEmpty()甚至myString.isBlank().
对此有任何指导/建议吗?或者它只是"任何晃动你的船"?
提前感谢我的好奇心.:d
Cha*_*ham 36
不要使用myString == "",在java中myString.equals("")这也是不推荐的.
isBlank是不一样的isEmpty,它实际上取决于你的用例.
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
Run Code Online (Sandbox Code Playgroud)
Eri*_*ber 16
对于String?(nullable String)数据类型,我用.isNullOrBlank()
对于String,我使用 .isBlank()
为什么?因为大多数时候,我不想允许带有空格的字符串(并.isBlank()检查空格和空字符串).如果您不关心空格,请使用.isNullorEmpty()和.isEmpty()String?和String,分别.
小智 6
Kotlin 中有两种可用的方法。
区别在于:
data = " " // this is a text with blank space
println(data.isNullOrBlank()?.toString()) //true
println(data.isNullOrEmpty()?.toString()) //false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17762 次 |
| 最近记录: |