Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin nullable generic

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)
   }
like image 744
Makc Avatar asked Mar 03 '26 04:03

Makc


1 Answers

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
    }
}
like image 139
Tenfour04 Avatar answered Mar 05 '26 06:03

Tenfour04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!