Hello - I am upgrading a project from Kotlin 1.3.7...
# announcements
t
Hello - I am upgrading a project from Kotlin 1.3.72 to 1.4.21. As part of this, I had some code of the form
val x = foo() ?: return moo
, where
foo(): T?
is a method returning a nullable generic
T?
. Now previously,
x
was of type
T
, however now the IDE is telling me that it is of type
T!!
. I can seemingly force it to be of type
T
, however can somebody explain what is going on here? I also can't find the relevant part of documentation that explains what
!!
means when postfixing a (possibly only generic?) type. Thanks!
m
Can you share a screenshot? A type should never be inferred to be
Something!!
. That’s probably either an IDE bug or a compiler bug.
t
This extra level of indirection seems to be required to actually get a compile error:
image.png
(The pop-up window isn't getting screenshotted for some reason!)
But it is happy with this:
image.png
m
Can you share as text so we can play with it? đŸ™‚ You should enable type hints so that you see the type directly in IDE editor. Preferences > Editor > Inlay Hints > Kotlin > Types > Show hints for > Local variable types
t
Copy code
data class Wrapper<T>(val value: T)

class Moo<T> {
    fun moo(): T? {
        return null
    }

    fun foo(): List<Wrapper<T>> {
        val x = moo() ?: return listOf()
        val list = mutableListOf<Wrapper<T>>()
        list.add(Wrapper(x))
        return list
    }
}
m
Yeah looks like a compiler bug.
Minimal repro:
t
(I'm generally happy just using ctrl-shift-P personally đŸ™‚ but yep:
image.png
m
wait
maybe it’s even correct
hmm. It’s actually good
T
is nullable. So
T!!
literally means a
non-null T
.
t
Ah- yep (makes sense after your edit)
Right - so I need to do something like this to ensure that
T
actually means a type that isn't null:
class Moo<T: Any>
. Then the compiler is happy that
Wrapped<T!!>
is the same as
Wrapped<T>
, I think.
Thanks very much!
m
Thank you too đŸ™‚