True, False, ¯\_(ツ)_/¯
| Colin DoddIf this is true, do this. If this is false, do that. But what about null?
If the user is logged in, show the “My Profile” button. If the user isn’t logged in, show the “Log In” button. It’s such a common thing to do that I’ve probably done it thousands, if not tens of thousands of times. It's so common there are even jokes about it.
One of the major advantages of Kotlin is that it distinguishes between nullable objects and non-nullable objects. This includes the Boolean type:
private fun example() {
val isLoggedIn = tryLogin()
if (isLoggedIn) { /**/ }
}
// returns: Nullable Boolean
private fun tryLogin(): Boolean? { /**/ }
Except, this doesn’t work because isLoggedIn
can now be in three states, true,
false, and null. Whereas the if
statement only works with non-nullable
booleans. We can rectify this by explicitly checking the state:
if (isLoggedIn == true)
This works, and is readable, but when code reviewing it can be hard to distinguish this from a new beginner mistake, causing it to be incorrectly flagged as an error. That said, this seems to be the recommended suggestion from the Kotlin style guide.
An alternative that may be preferable, is to use when
:
when(isLoggedin) {
true -> {}
false -> {}
null -> {}
}
// This works well if you want to branch based on the state of the boolean, but perhaps is a bit too verbose if you only want to do something in only one of the booleans states.