How to set null for generics in Kotlin

In my application I used ViewBinding for access to views and for this I create Base Fragment and write below codes.
In onDestroy method I want null the views but show me error.
My BaseFragment codes:

abstract class BaseFragment<T : ViewBinding>(private val bindingInflater: (inflater: LayoutInflater) -> T) : Fragment() {

    var isNetworkAvailable = true

    private lateinit var viewBinding: T

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewBinding = bindingInflater(inflater)
        return viewBinding.root

    override fun onDestroy() {
        viewBinding = null

Show me this error Null can not be a value of a non-null type T in this line viewBinding = null .

How can I fix it?

>Solution :

If you want to declare nullable a type or a variable, you should use the ?, right after your type declaration.

Following this documentation

val string : String = null  --> Nope, String is not nullable
val string : String? = null --> Yes, String is nullable

To assign a null value to a variable or a type you must declare it nullable.

Leave a Reply