以下两种实现方式哪一个更好:
1.使用“if”
fun f1(a: A?): R? {
if (a != null) {
val b = getB(a)
if (b != null && b.f()) {
val c = getC(b)
if (c != null && c.f()) {
return c.f2()
}
}
}
return null
}
2.使用“takeIf”和“let”
fun f2(a: A?): R? = a
?.let { getB(it) }
?.takeIf { it.f() }
?.let { getC(it) }
?.takeIf { it.f() }
?.let { it.f2() }
最佳答案
这是一个主观问题。有些人喜欢一种版本,另一些人则喜欢另一种版本。 就我个人而言,我认为这更具可读性:
fun f3(a: A?): R? {
if (a == null) {
return null
}
val b = getB(a)
if (b == null || !b.f()) {
return null
}
val c = getC(b)
if (c == null || !c.f()) {
return null
}
return c.f2()
}
关于kotlin - Kotlin 中的 "if"与 "takeIf"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173227/