I am trying to learn the "Kotlin native way" to do things in Android, while being an expert in neither Kotlin, Java, nor Android development. Specifically, how to properly deal with nullability in Android interfaces/extensions.
Below is a snippet of a working example using a RecyclerView that seems to be abusing Kotlin's nullability paradigm.
Adapter:
First, the Adapter class:
class PersonListAdapter(private val list: ArrayList<Person>,
private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
Note: this example uses ArrayList<>, instead of ArrayList<>?.
Main Activity:
Then in the main activity, it has the following snippet:
private var adapter: PersonListAdapter? = null
private var personList: ArrayList<Person>? = null
private var layoutManager: RecyclerView.LayoutManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
personList = ArrayList<Person>()
layoutManager = LinearLayoutManager(this)
adapter = PersonListAdapter(personList!!, this)
Notice here two things: (1) personList is an ArrayList<>? (note the nullability), and (2) the list is later called with personList!!, basically escaping us out of the whole point of safely using nullable objects in Kotlin.
Options??
I don't understand why the author did this. Why not simply assign the list to something non-null initially? For instance, something like:
private var personList = ArrayList<Person>()
Or, if this cannot easily be done, why not initialize the adapter with a nullable list? I'm presuming the latter cannot be done because we're extending the RecyclerView.Adapter, but I wanted to ask to be sure. I am thinking something like the following:
class PersonListAdapter(private val list: ArrayList<Person>?,
private val context: Context) : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
(Note the ArrayList<Person>? instead of ArrayList<Person>.)
Or is there an even better paradigm?
Summary
What's the right way to handle nullability in Kotlin when working with Android interfaces, extensions, and other situations where we're building on top of a deep base of Java code?
I'd really like to avoid using !! whenever possible. While I am a newbie in this realm, it seems to me that the point of the ? is to avoid the billion dollar mistake, and that using !! is essentially saying, "nope, I want that billion dollar mistake back", isn't it?