Mina Racic
02/27/2022, 10:27 AMDerek Peirce
02/27/2022, 10:47 AMif (x) return y
pattern by only two characters?hfhbd
02/27/2022, 10:59 AM? :
syntax (ternary operator) is not used in Kotlin before, and is unlikely to be introduced: https://kotlinlang.org/docs/control-flow.html#if-expressionFleshgrinder
02/27/2022, 11:23 AM?
in the context of bool is a bad idea for the consistency of the language, as it always is about null
in every other context.Fleshgrinder
02/27/2022, 11:23 AMnull
you don't need it: a ?: return b
Mina Racic
02/27/2022, 11:45 AMc ?: return d
it’s not the same use-case we return c if it’s not null but in return? a : b
we return b if a expression is truehfhbd
02/27/2022, 12:05 PMif (a) return b
read as: if a is true, return b. From left to right, reading follows code execution, first condition, then the optional action and its value.
return? a : b
read as: return b if a is true. To understand the effect, you must read the optional action first, then the condition, and then the value used by the action. Reading does not follow the code execution. With complex expression, this is harder to understand, especially for a newcomer.
if (oldUser == null || newUser == null || repo == null) return null
return? oldUser == null || newUser == null || repo == null : null
Mina Racic
02/27/2022, 12:11 PMMina Racic
02/27/2022, 12:14 PMhfhbd
02/27/2022, 12:22 PMjanvladimirmostert
03/01/2022, 7:27 AMfun <T : Any?> runIf(b: Boolean, runIt: () -> T): T? {
return if (b) {
runIt.invoke()
} else {
null
}
}
fun main() {
val a = runIf(true) {
"testing 1"
}
println(a) // prints testing 1
val b = runIf(false) {
"testing 1"
}
println(b) // prints null
}
janvladimirmostert
03/01/2022, 7:28 AM