If I have: ``` class Auto(val isNew: Boolean) val ...
# announcements
a
If I have:
Copy code
class Auto(val isNew: Boolean)
val car: Car? = Car(true)
why the following code works:
Copy code
if (car?.isNew == true) println("new car")
and the following doesn't compile:
Copy code
if (car?.isNew) println("new car")
d
car?.isNew
returns a
Boolean?
instead of
Boolean
which
if
requires.
==
returns
Boolean
.
☝️ 2
a
and if you want to avoid writing
car?.isNew == true
in favour of something more elegant you could do:
if (car?.isNew ?: false)
which will return
false
in case
car
is
null
👍 1
d
I would argue that
car?.isNew == true
states the intent more clearly: The code runs if
isNew
is true.
☝️ 4
👍 1
a
OK, thanks, I understand now. But it looks weird
if (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)
k
Yeah, I disagree with @diesieben07 and the InteliJ inspection: I think
?: false
is better because it emphasizes what happens if it's
null
. In the end it's just an opinion 🤷‍♂️
☝️ 3
d
Your first course in programming wasn't in a null safe language like Kotlin though ;)
😄 6
But yes, Karel is right, in the end it's a matter of opinion
🙏 1
b
It is, but the kotlin coding conventions state that you should use
nullable == 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-conditions
👍 5
t
maybe then this is a bug in intellij inspector, if it suggests things contrary to convention it is not good. if I have to check what is the convention for every piece of code I write I would be a sloth, if intellij warns me I will learn by assimilation at some point
k
No Intelij does suggest
?: false
->
== true
as per the official convention.
t
I misread you, there was an
and
I missed
a
I think the main source of confusion in the case of
nullable == true
(why it works) is the fact that Kotlin does a little magic here:
Copy code
a == b is translated to:
a?.equals(b) ?: (b === null)
source: https://kotlinlang.org/docs/reference/equality.html#structural-equality 🤯
k
Well arguably that's not really magic, that just makes
==
behave as expected instead of throwing nullpointers like Java's
equals
.
a
that
just 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.