androidadventures

Cool things I learned, Part 2 - Properties in Kotlin

Say you're using a RecyclerView and wanted to call notifyDataSetChanged every time the data updates. Or say you want to fetch a list every time the location changes. Yes, I know Compose is the new thing but this is just a general example.

So, in your adapter you have a list that will be updated often.


var list = mutableListOf<String>()
  set(value) {
    field = value
    notifyDataSetChanged()
  }

Another example:


  var location: Pair<Double, Double> = Pair(1.0, 1.0)
    set(value) {
    field = value
    fetchRestaurants()
  }

Custom setter are not supported with lateinit is something to keep in mind.

Really trivial thing, but really useful

Thoughts? Leave a comment