Wrong return type when pass nullable generic type value to Java constructor

It’s ok to pass null to a Java method when there is no Nullable annotation on generic type parameter, but if it’s a constructor, IDE show me error, but it compiles!

For some reason, We need pass type T? as parameter to Java constructor which Nullable not specified. Example:

fun <T : Any> T?.weakRef(): WeakReference<T> {
    return WeakReference<T>(this) // ide show error but compiles.
}

Kotlin and plugin version: 1.3.70

If the IDE is complaining but not the compiler, it could be the new type inference kicking in (blog post) . You can disable it in your IDEA compiler settings.

1 Like

Yes, this is new inference. You can disable it in the IDE in “File | Settings | Build, Execution, Deployment | Compiler | Kotlin Compiler”.

Also tested with pre-release internal version 1.4-M1-eap-93, it’s fixed there. So in the next 1.4-M1 the error will not appear.

1 Like

Good, just lost this disable setting after upgraded IDE, now it fixed again. Thanks.