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

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() {

    //Other
    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() {
        super.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?

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 :

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.

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