```?.takeIf { id -> session.classFromId(id)?.is...
# getting-started
m
Copy code
?.takeIf { id -> session.classFromId(id)?.isAnnotationClass() == true }
Is there a version of
takeIf
that lets me return
Boolean?
or a better idiom to use here to obviate the
== true
?
y
== true
is the idiom here. Dealing with
Boolean?
Is hard. There's no simple rule as to what
null
should map to. Sometimes you genuinely want to use
== false
. If the expression gets big enough, early returns can be very helpful:
Copy code
?.takeIf { id ->
  val klass = session.classFromId(id) ?: return@takeIf false
  klass.isAnnotationClass()
}
❤️ 1
g
Why not
Copy code
?.takeIf { id -> 
  session.classFromId(id)?.isAnnotationClass() ?: false 
}
or (depending on your logic)
Copy code
?.takeIf { id -> 
  session.classFromId(id)?.isAnnotationClass() 
} ?: false
y
That works as well, and is equivalent I vaguely remember the
==
pattern being considered more idiomatic for some reason, but hey it's all personal preference at the end of the day
o
This kind of question is what AI is used for
👎🏻 1
e
https://kotlinlang.org/docs/coding-conventions.html#nullable-boolean-values-in-conditions official codestyle recommends
If you need to use a nullable
Boolean
in a conditional statement, use
if (value == true)
or
if (value == false)
checks.
https://github.com/Kotlin/kotlin-style-guide/issues/18 not everybody agreed but I find it clearer to use `==
/
!=` because it makes it clear which of the 3 cases you are treating uniquely