https://kotlinlang.org logo
#getting-started
Title
# getting-started
w

wck

06/11/2022, 1:54 AM
Hi guys, has something changed in 1.6.21 regarding nullables? code posted in thread.
Copy code
class Test {
    fun <T: Any?> nullableFun(): T {
        return null as T
    }
    @Test
    fun testNull() {
        assertTrue {
            val a = nullableFun<String>()
            a?.length == null
        }
    }
    @Test
    fun testNull2() {
        assertTrue {
            nullableFun<String>()?.length == null
        }
    }

}
both tests passed in 1.6.10, however
testNull
failed with NPE in 1.6.21,
testNull2
still passed
e

ephemient

06/11/2022, 2:59 AM
it could be a side effect of the definitely not-null feature, however your code is bad in all cases, it should either be
Copy code
fun <T: Any> nullableFun(): T?
fun <T> nullableFun(): T?
because what you currently have implies that
nullableFun<String>(): String
which is wrong (but can't be checked in the function itself due to generics)
w

wck

06/11/2022, 3:11 AM
The code is made intentionally to reproduce the NPE
I'm just curious on whats the difference between those, it crashes if it's assigned to a val
Shouldn't the behavior of those be the same
e

ephemient

06/11/2022, 3:33 AM
in the first case, it's equivalent to
Copy code
val a: String =
for which the compiler will insert a check in various cases
👍 2
w

wck

06/11/2022, 3:51 AM
thanks a lot, that makes sense. So what about the second case? couldn’t find too much information on this one, reading the
Definitely non-nullable types
doesn’t seem to be quite related
e

ephemient

06/11/2022, 3:53 AM
I agree the compiler isn't being consistent and that definitely non-nullable types doesn't directly impact this case, but it's the only type-related change I spotted in the changelog so it's possible this was a side effect
w

wck

06/19/2022, 6:51 AM
@ephemient https://youtrack.jetbrains.com/issue/KT-52743 This is now confirmed as a major bug if you are still interested