https://kotlinlang.org logo
Title
a

aphex

03/30/2017, 1:45 PM
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

robin

03/30/2017, 1:58 PM
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

aphex

03/30/2017, 2:03 PM
AWESOME :kotlin:❤️
r

robin

03/30/2017, 2:06 PM
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

aphex

03/30/2017, 2:10 PM
Hahah yeah, and then it suggests I introduce
activity
as an argument to when. Fix this lint-check, @jetbrains 😆
r

robin

03/30/2017, 2:10 PM
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