gpt4 book ai didi

kotlin - 如何在 Kotlin 中惯用地测试非空、非空字符串?

转载 作者:IT老高 更新时间:2023-10-28 13:30:10 26 4
gpt4 key购买 nike

我是 Kotlin 的新手,我正在寻求帮助,将以下代码重写为更优雅。

var s: String? = "abc"
if (s != null && s.isNotEmpty()) {
// Do something
}

如果我使用以下代码:

if (s?.isNotEmpty()) {

编译器会提示

Required: Boolean
Found: Boolean?

谢谢。

最佳答案

您可以使用 isNullOrEmpty或其 friend isNullOrBlank像这样:

if(!s.isNullOrEmpty()){
// s is not empty
}

isNullOrEmptyisNullOrBlank 都是 CharSequence? 上的扩展方法,因此您可以安全地与 null 一起使用它们。或者像这样将 null 变成 false:

if(s?.isNotEmpty() ?: false){
// s is not empty
}

你也可以这样做

if(s?.isNotEmpty() == true){ 
// s is not empty
}

关于kotlin - 如何在 Kotlin 中惯用地测试非空、非空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41162797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com