https://kotlinlang.org logo
Title
b

Benoit Duffez

11/03/2018, 9:15 PM
fun foo(bar: Long) { ... }
//elsewhere:
fun whatever(baz: Long?) = return when {
  baz ?: 0 > 0 -> foo(baz) // here
  else -> null
}
why is there no smart cast for baz being non null here?
k

karelpeeters

11/03/2018, 9:21 PM
The compiler simply doesn't try to be too smart about stuff like this.
b

Benoit Duffez

11/03/2018, 9:26 PM
OK, thanks for the reply
I don't like the
!!
operator but I guess it is safe here.
k

karelpeeters

11/03/2018, 9:27 PM
Can't you just do
baz != null && baz > 0
or something?
h

hudsonb

11/03/2018, 9:46 PM
Or maybe change whatever to whatever(baz: Long) and use baz ?: 0 at the call site.
b

Benoit Duffez

11/04/2018, 12:45 PM
the question was more about why the compiler doesn't smart cast rather than how to deal with the consequences
k

kingsley

11/04/2018, 5:35 PM
But there’s nothing to smart-cast. If
baz
was
null
, it still continues to be
null
k

karelpeeters

11/04/2018, 5:36 PM
Yes, but if
baz ?: 0 > 0
then
baz
is certainly not null.
👍 1
k

kingsley

11/04/2018, 5:37 PM
Aha. Right. Missed that