gpt4 book ai didi

android - Kotlin 和惯用的编写方式, 'if not null, else...' 基于可变值

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

假设我们有这样的代码:

class QuickExample {

fun function(argument: SomeOtherClass) {
if (argument.mutableProperty != null ) {
doSomething(argument.mutableProperty)
} else {
doOtherThing()
}
}

fun doSomething(argument: Object) {}

fun doOtherThing() {}
}

class SomeOtherClass {
var mutableProperty: Object? = null
}

与在 Java 中不同的是,在 Java 中,您可能会独自担心在运行时取消引用 null,这不会编译 - 非常正确。当然,mutableProperty 在 'if' 中可能不再为 null。

我的问题是处理这个问题的最佳方法是什么?

一些选项是显而易见的。在不使用任何新的 Kotlin 语言功能的情况下,最简单的方法显然是将值复制到方法范围内,该值随后不会更改。

有这个:

fun function(argument: SomeOtherClass) {
argument.mutableProperty?.let {
doSomething(it)
return
}
doOtherThing()
}

这有一个明显的缺点,即您需要提前返回或避免执行后续代码 - 在某些小型上下文中可以,但有异味。

那么就有这种可能:

fun function(argument: SomeOtherClass) {
argument.mutableProperty.let {
when {
it != null -> {
doSomething(it)
}
else -> {
doOtherThing()
}
}
}
}

虽然它的目的更清晰,但可以说它比 Java 风格的处理方式更加笨拙和冗长。

我是否遗漏了什么,是否有一个首选的成语来实现这一点?

最佳答案

更新:

正如franta在评论中提到的,如果方法doSomething()返回null,那么elvis运算符右侧的代码将被执行,这可能不是你想要的情况最多。但同时,在这种情况下,doSomething() 方法很可能只会做某事而不会返回任何内容。

还有一个替代方案:正如 protossor 在评论中提到的那样,可以使用 also 而不是 let,因为 also 返回 this 对象而不是功能 block 的结果。

mutableProperty?.also { doSomething(it) } ?: doOtherThing()

原答案:

我会使用 letElvis operator .

mutableProperty?.let { doSomething(it) } ?: doOtherThing()

来自文档:

If the expression to the left of ?: is not null, the elvis operator returns it, otherwise it returns the expression to the right. Note that the right-hand side expression is evaluated only if the left-hand side is null.

右侧表达式后面的代码块:

   mutableProperty?.let {
doSomething(it)
} ?: run {
doOtherThing()
doOtherThing()
}

关于android - Kotlin 和惯用的编写方式, 'if not null, else...' 基于可变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45877140/

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