我的意思是从技术上讲,你可以像这样设置一些疯狂的功能:
inline fun <A, R> guardLet(pairA: Pair<A?, (A) -> Boolean>, block: (A) -> R): R? {
val (a, aPredicate) = pairA
if(a != null && aPredicate(a)) {
return block(a)
}
return null
}
inline fun <A, B, R> guardLet(pairA: Pair<A?, (A) -> Boolean>, pairB: Pair<B?, (B) -> Boolean>, block: (A, B) -> R): R? {
val (a, aPredicate) = pairA
val (b, bPredicate) = pairB
if(a != null && b != null && aPredicate(a) && bPredicate(b)) {
return block(a, b)
}
return null
}
并将其称为
guardLet(someProperty to { it != "blah" }, otherProperty to { it.something() }) { somePropertyByCondition, otherPropertyByCondition ->
...
} ?: return
虽然在这种特殊情况下你可以使用这个:
inline fun <R, A> ifNotNull(a: A?, block: (A) -> R): R? =
if (a != null) {
block(a)
} else null
inline fun <R, A, B> ifNotNull(a: A?, b: B?, block: (A, B) -> R): R? =
if (a != null && b != null) {
block(a, b)
} else null
inline fun <R, A, B, C> ifNotNull(a: A?, b: B?, c: C?, block: (A, B, C) -> R): R? =
if (a != null && b != null && c != null) {
block(a, b, c)
} else null
inline fun <R, A, B, C, D> ifNotNull(a: A?, b: B?, c: C?, d: D?, block: (A, B, C, D) -> R): R? =
if (a != null && b != null && c != null && d != null) {
block(a, b, c, d)
} else null
然后就去吧
ifNotNull(
snapshot.child("type").value as? String,
UnitEnumType.values().firstOrNull { it.abbrv == type },
snapshot.child("image_url").value as? String) { type, unitType, imageUrl ->
...
} ?: return
我不知道,我只是在向你抛出各种可能性。