3

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

1 Answer 1

7

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am not sure that you have seen my reply on my deleted answer, just wanted to thank you for the explaining and linking the not-nullable generic feature
@Steyrix, I saw it, you're welcome

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.