Hi all, the following code snippet doesn't compile...
# announcements
t
Hi all, the following code snippet doesn't compile due to the possibility of an unchecked null, even though I'm definitely accommodating for null. This is a cut down version of the issue when I found it in my code base. Is there something I'm overlooking? The associated error:
Copy code
try-catch-null-check.kt:22:24: error: operator call corresponds to a dot-qualified call 'nullableVal.plus(1)' which is not allowed on a nullable receiver 'nullableVal'.
	val sum = nullableVal + 1
                       ^
What's more interesting is if I do
dummy!!
on line 15, I get this warning:
Copy code
try-catch-null-check.kt:15:8: warning: unnecessary non-null assertion (!!) on a non-null receiver of type Int
		dummy!!
       ^
I can also explicitly specify the type of the try/catch and it works fine:
val nullableVal: Int = try {
r
You can also work around it by using an else block in
try
t
hmm yes, let me see if that works
yea using else works, curiously
this seems like a bug involving the last-line return in the try/catch. If the compiler is smart enough to know I don't need that
!!
on
dummy
, then it's certainly smart enough to know I'm doing the null check
r
The type checker uses the returned type of the values to infer. While you are checking if
dummy
is null, you are returning it outside the check where it is still
Int?
, so that's the inferred type
t
yes
is the early return not enough to say "`dummy` cannot possibly be null at this point (line 15)"?
r
It's not a bug per say, but it could be smarter. I'd file an issue anyway and see what they say about it.
t
yea just making sure i'm not insane
r
Well, I can't rule that out 🙂
t
hours upon hours of debugging makes one question reality
d
Yes, that’s a known issue with type inference, where it doesn’t use a smartcast for inferring type. We’re thinking of how we can fix it in the new inference algorithm on which we’re working currently, but the issue is a bit more trickier than it may appear. For now, the easiest workaround is to specify type for
nullableVal
explicitly as
Int
(as actually, you make sure that its
nonnullableVal
🙂 )