Skip to content

Instantly share code, notes, and snippets.

@TarodBOFH
Last active November 11, 2018 22:06
Show Gist options
  • Select an option

  • Save TarodBOFH/40dd67511140e249a60d6f40b9259d1a to your computer and use it in GitHub Desktop.

Select an option

Save TarodBOFH/40dd67511140e249a60d6f40b9259d1a to your computer and use it in GitHub Desktop.
fun main() {
// You can do this
val assignment = null ?: false
val fromBlock = when(assignment) {
true -> true
false -> null
} ?: false
// Or this
val computed = if (fromBlock && assignment) { true } else { null }
// see the outputs
println("assignment $assignment")
println("fromBlock $fromBlock")
println("computed $computed")
println("safe-output is ${computed ?: false}")
// Never do this
val b1 = nullableFun(true)
val b2 = nullableFun(false)
val b1b2 = b1 != b2 // this is confusing! are they Boolean or null?
// Neither do this
val b3 = b1 != b2 ?: false
// Again, ok to do this
val bok1 = b1 ?: true
val bok2 = b2 ?: false
//see the outputs...
listOf(b1,b2,b1b2,b3,bok1,bok2).forEach { println(it) }
}
fun nullableFun(b: Boolean): Boolean? = if ( (0..1).shuffled().first() == 0) { b } else { null }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment