Cra*_*tis 8 nullable tostring conditional-statements kotlin
我有一个可以为null的属性(一个Java对象)知道如何将自己转换为String,如果这个表示不为空,我想用它做一些事情.在Java中,这看起来像:
MyObject obj = ...
if (obj != null) {
String representation = obj.toString();
if (!StringUtils.isBlank(representation)) {
doSomethingWith(representation);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在努力寻找将此转换为Kotlin的最惯用的方式,我有:
with(obj?.toString()) {
if (!isNullOrBlank()) {
doSomethingWith(representation)
}
}
Run Code Online (Sandbox Code Playgroud)
但对于这样一个简单的操作,它仍然感觉太多了.我有这种感觉,结合let,when和with我可以苗条下来的东西有点短.
步骤是:
我试过了:
when(where?.toString()) {
isNullOrBlank() -> builder.append(this)
}
Run Code Online (Sandbox Code Playgroud)
但是(1)它失败了:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: @InlineOnly public inline fun
CharSequence?.isNullOrBlank(): Boolean defined in kotlin.text @InlineOnly public inline fun CharSequence?.isNullOrBlank(): Boolean defined in
kotlin.text
Run Code Online (Sandbox Code Playgroud)
即使它已经过去了,(2)它也会想要详尽无遗else,我并不真正关心这一点.
什么是"Kotlin方式"?
Jay*_*ard 13
您可以使用(自Kotlin 1.1开始)内置的stdlib takeIf()或takeUnless扩展,可以使用:
obj?.toString().takeUnless { it.isNullOrBlank() }?.let { doSomethingWith(it) }
// or
obj?.toString()?.takeIf { it.isNotBlank() }?.let { doSomethingWith(it) }
// or use a function reference
obj?.toString().takeUnless { it.isNullOrBlank() }?.let(::doSomethingWith)
Run Code Online (Sandbox Code Playgroud)
为了doSomethingWith()对最终值执行操作,您可以使用apply()在当前对象的上下文中工作,返回是同一个对象,或者let()更改表达式的结果,或者run()在当前对象的上下文中工作,以及更改表达式的结果,或also()在返回原始对象时执行代码.
如果您希望命名更有意义,也可以创建自己的扩展功能,例如nullIfBlank()可能是一个好名字:
obj?.toString().nullIfBlank()?.also { doSomethingWith(it) }
Run Code Online (Sandbox Code Playgroud)
这被定义为可空的扩展String:
fun String?.nullIfBlank(): String? = if (isNullOrBlank()) null else this
Run Code Online (Sandbox Code Playgroud)
如果我们再添加一个扩展名:
fun <R> String.whenNotNullOrBlank(block: (String)->R): R? = this.nullIfBlank()?.let(block)
Run Code Online (Sandbox Code Playgroud)
这允许将代码简化为:
obj?.toString()?.whenNotNullOrBlank { doSomethingWith(it) }
// or with a function reference
obj?.toString()?.whenNotNullOrBlank(::doSomethingWith)
Run Code Online (Sandbox Code Playgroud)
您总是可以编写这样的扩展来提高代码的可读性.
注意:有时我使用?.null安全访问器,有时则不使用.这是因为某些函数的predicat/lambdas使用可空值,而其他函数则没有.您可以按照自己的方式设计这些.由你决定!
有关此主题的更多信息,请参阅: 处理nullables的惯用方法
| 归档时间: |
|
| 查看次数: |
879 次 |
| 最近记录: |