``` val newFragment: Fragment? = if (fragm...
# codereview
o
Copy code
val newFragment: Fragment? = if (fragment is CarSearchFragment? && fragment == null) {
            CarSearchFragment()
        } else if (fragment is CarValuationFragment? && fragment == null) {
            CarValuationFragment()
        } else if (fragment is HotDealsFragment? && fragment == null) {
            HotDealsFragment()
        } else if (fragment is FavoritesFragment? && fragment == null) {
            FavoritesFragment()
        } else {
            fragment
        }
l
This code doesn't work. You can't really do
is
check on
null
. Doesn't the IDE warns you about this?
o
ahh that’s right,
is
is for type not value
yea no I dont get a warning
what Im looking for is how to do && in
when
I guess
d
Copy code
val newFragment = if(fragment != null) {
  when() {
    ...
  }
} else {
  fragment
}
or
Copy code
val newFragment = fragment ?: when(fragment) {
  ...
}
Maybe one of these?
o
hmm yea
d
There’s probably another way to improve it because it looks like you are just creating an instance of a particular class when it’s null. ie. you could probably add a function on the companion object that would create an instance of the class if it’s null, so it could be written like
val newFragment = fragment.initIfNull()
or something, and that lets you avoid doing all the type checking which generally is good to avoid for OO-design.
o
let me try that yea
s
this seems like a broader design problem or at least an a XY issue - you can’t really do cascading type checks on
null
and this much type checking is no bueno in general unless you’re working with enum or sealed classes with minimal state
a
the following could doesn't work:
Copy code
val newFragment = fragment?.let { when(it) {
    is CarSearchFragment? -> CarSearchFragment()
    is CarValuationFragment? -> CarValuationFragment()
   ...
}
s
I’m pretty sure
null
will always hit the first branch of the when regardless of what type it might’ve had at the call site
a
nevermind, you are right. Its always the first branch
👍 1
o
Exactly what was happening to me