fun <T: Any?> function(input: T): T = input
fun function2() {
val n = function(1)!!
}
Since T is declared as nullable, I expected the output to be nullable as well, but Lint produces Unnecessary non-null assertion (!!) on a non-null receiver of type Int warning.
Changing the output type signature to T? makes the warning go away.
Why does the output type not conform to the declaried nullability?
T: Any?does not mean "Tis nullable". It constrains the type parameterTto be a subtype ofAny?. Nullable types, as well as non-nullable types satisfy this constraint. In general, ifBis a subtype ofA, thenA,B,A?, andB?are all subtypes ofA?.When you do
The type parameter
Tis inferred to beInt, which is a non-nullable type that satisfies the constraint: Any?. The function is declared to return aT, so in this case it returns anInt. There are no problems here, and!!is unnecessary.Compare that to:
where you explicitly say that
Tshould beInt?, which is a nullable type (that also satisfy the constraint of: Any). In this case the function returnsInt?, and!!can be added without a warning.