``` fun fromActivity(activity: Activity?): Source ...
# getting-started
a
Copy code
fun fromActivity(activity: Activity?): Source = when {
                activity != null && activity is FooActivity -> Source.FOO
                else -> Source.UNKNOWN
            }
Something tells me I don’t need the null check in the above code. Can I get rid of it and have the same exact behavior?
(feel free to respond in a thread so both of our questions don’t collide)
r
Yeah, you can just remove the null check. The
is
check won't succeed if
activity
is null.
You can even have
activity
as a parameter to the
when
expression then.
a
AWESOME K❤️
r
Actually, if you flip the
&&
expression in your code so that it looks like this:
activity is FooActivity && activity != null
intelliJ will even tell you that the null-check is unnecessary 😉
a
Hahah yeah, and then it suggests I introduce
activity
as an argument to when. Fix this lint-check, @jetbrains 😆
r
Why fix it? Works as it should 😄
If you mean that it doesn't catch your original situation, that's intended - there are legit cases where you actually want both checks, for example if the second check is much more expensive and you want to short-circuit it if the first check already passes, even if it was technically covered by the second one.
👍 1