Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)
   }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading