Last active
November 11, 2018 22:06
-
-
Save TarodBOFH/40dd67511140e249a60d6f40b9259d1a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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