Travis Griggs
02/05/2020, 10:45 PMif let foo = someOptionalExpression, let bar = optionalExpression(foo) {
// work with foo AND bar
}
else {
// deal with nil/null case
}
Zach Klippenstein (he/him) [MOD]
02/05/2020, 10:46 PMsomeOptionalExpression?.let { foo ->
optionalExpression(foo)?.let { bar ->
// work with foo and bar
}
} ?: // deal with null case
Travis Griggs
02/05/2020, 10:48 PM// work with foo and bar
returns null
then the handler will fire?Zach Klippenstein (he/him) [MOD]
02/05/2020, 10:50 PMZach Klippenstein (he/him) [MOD]
02/05/2020, 10:51 PMval foo = someOptionalExpression
val bar = foo?.let { optionalExpression(it) }
if (foo != null && bar != null) {
…
} else {
…
}
Tim Malseed
02/05/2020, 10:53 PMIsn’t it the case that ifI believe that is not correct, as there’s nothing that handlesreturns// work with foo and bar
then the handler will fire?null
optionalExpression(foo)
being evaluated to null
Tim Malseed
02/05/2020, 10:55 PMexpressionA?.let { foo ->
expressionB(foo)?.let { bar ->
expressionC
} ?: // deal with expressionB or C evaluating to null
} ?: // deal with expressionA evaliating to null
Tim Malseed
02/05/2020, 10:56 PMTravis Griggs
02/05/2020, 10:57 PMif let...
expressions, but I've struggled with how to use the same pattern when there are multiple conditions, especially when the conditions are cumulativeTim Malseed
02/05/2020, 10:58 PMTim Malseed
02/05/2020, 10:58 PMtakeIf()
Tim Malseed
02/05/2020, 10:59 PMTim Malseed
02/05/2020, 11:01 PMinline fun <T1 : Any, T2 : Any, R : Any> biLet(p1: T1?, p2: T2?, block: (T1, T2) -> R?): R? {
return if (p1 != null && p2 != null) block(p1, p2) else null
}
Tim Malseed
02/05/2020, 11:02 PMbiLet(optionalA, optionalb) { a, b ->
}
Travis Griggs
02/05/2020, 11:02 PMfun <T>optionalOne(arg:T, beNull:Boolean) : T? {
return if (beNull) { null } else { arg }
}
fun <T>optionalTwo(arg:T, beNull:Boolean) : T? {
return if (beNull) { null } else { arg }
}
@Test
fun testStuff() {
this.optionalOne(2, false)?.let { one ->
this.optionalTwo(13, true)?.let { two ->
"RESULT IS ${one * two}".print()
}
} ?: run {
"FAILURE BLOCK".print()
}
}
Tim Malseed
02/05/2020, 11:02 PMTim Malseed
02/05/2020, 11:03 PMthis.optionalTwo(13, true)
is nullTravis Griggs
02/05/2020, 11:03 PMTravis Griggs
02/05/2020, 11:03 PMAlowaniak
02/05/2020, 11:50 PMlet
with also
@Tim Malseed the optionalExpression(good)
evaluating to null will cause the outer let
to evaluate to null and thus the handler will fireTim Malseed
02/05/2020, 11:54 PMcodeslubber
02/06/2020, 3:11 PM