andrzej
10/29/2019, 11:10 AMclass Auto(val isNew: Boolean)
val car: Car? = Car(true)
why the following code works:
if (car?.isNew == true) println("new car")
and the following doesn't compile:
if (car?.isNew) println("new car")
Dominaezzz
10/29/2019, 11:13 AMcar?.isNew
returns a Boolean?
instead of Boolean
which if
requires. ==
returns Boolean
.Alessandro Mautone
10/29/2019, 11:16 AMcar?.isNew == true
in favour of something more elegant you could do:
if (car?.isNew ?: false)
which will return false
in case car
is null
diesieben07
10/29/2019, 11:17 AMcar?.isNew == true
states the intent more clearly: The code runs if isNew
is true.andrzej
10/29/2019, 11:37 AMif (car?.isNew == true)
, like you know on your first course on programming you learn that you should write if(car.isNew)
instead of if(car.isNew == true)
karelpeeters
10/29/2019, 11:40 AM?: false
is better because it emphasizes what happens if it's null
. In the end it's just an opinion 🤷♂️diesieben07
10/29/2019, 11:41 AMdiesieben07
10/29/2019, 11:43 AMBurkhard
10/29/2019, 12:07 PMnullable == true
instead of nullable ?; false
. So even thoug I prefer the latter I use the first.
https://kotlinlang.org/docs/reference/coding-conventions.html#using-nullable-boolean-values-in-conditionsthanksforallthefish
10/29/2019, 12:14 PMkarelpeeters
10/29/2019, 12:26 PM?: false
-> == true
as per the official convention.thanksforallthefish
10/29/2019, 1:00 PMand
I missedandrzej
10/29/2019, 4:18 PMnullable == true
(why it works) is the fact that Kotlin does a little magic here:
a == b is translated to:
a?.equals(b) ?: (b === null)
source: https://kotlinlang.org/docs/reference/equality.html#structural-equality 🤯karelpeeters
10/29/2019, 7:40 PM==
behave as expected instead of throwing nullpointers like Java's equals
.andrzej
10/30/2019, 8:51 AMjust makes == behave as expected
I call magic. It shouldn't work when you look at it, knowing how operators in Kotlin work (how could you call equals
method on null), but it works.