https://kotlinlang.org logo
Title
o

oday

10/31/2018, 3:04 PM
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

louiscad

10/31/2018, 3:06 PM
This code doesn't work. You can't really do
is
check on
null
. Doesn't the IDE warns you about this?
o

oday

10/31/2018, 3:06 PM
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

dalexander

10/31/2018, 3:14 PM
val newFragment = if(fragment != null) {
  when() {
    ...
  }
} else {
  fragment
}
or
val newFragment = fragment ?: when(fragment) {
  ...
}
Maybe one of these?
o

oday

10/31/2018, 3:17 PM
hmm yea
d

dalexander

10/31/2018, 3:17 PM
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

oday

10/31/2018, 3:17 PM
let me try that yea
s

Shawn

10/31/2018, 4:25 PM
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

Andreas Sinz

11/01/2018, 10:19 AM
the following could doesn't work:
val newFragment = fragment?.let { when(it) {
    is CarSearchFragment? -> CarSearchFragment()
    is CarValuationFragment? -> CarValuationFragment()
   ...
}
s

Shawn

11/01/2018, 11:15 AM
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

Andreas Sinz

11/01/2018, 11:30 AM
nevermind, you are right. Its always the first branch
👍 1
o

oday

11/01/2018, 12:21 PM
Exactly what was happening to me