I am not understand why this code not working
class nullableGenericA<T: Any?>{
fun someMethod(v: T){}
fun someMethod(){
someMethod(null)
}
}
error: "Null can not be a value of a non-null type T". How it works? If nullable is not part of type why works this
class NullableGenericB<T>(val list: ArrayList<T>){
fun add(obj: T){
list.add(obj)
}
}
fun testNullableGenericB(){
NullableGenericB<String?>(ArrayList()).add(null)
}
CodePudding user response:
Your generic type is not necessarily nullable. It only has an upper bound of allowing nullable, but it is not constrained to be nullable. Since T
could possibly be non-nullable, it is not safe to pass null
as T
. For example, someone could create an instance of your class with non-nullable type:
val nonNullableA = NullableGenericA<String>()
If you want to design it so you can always use nullables for the generic type, then you should use T?
at the use sites where it is acceptable. Then, even if T
is non-nullable, a nullable version of T
is used at the function site.
class NullableGenericA<T>{
fun someMethod(v: T?) {}
fun someMethod() {
someMethod(null)
}
fun somethingThatReturnsNullableT(): T? {
return null
}
}