Jean-Michel Fayard
1 min readJun 13, 2017

--

One important trick missing are delegated properties https://kotlinlang.org/docs/reference/delegated-properties.html

Instead of

var recyclerView: RecyclerView? = null
val adapter : Adapter? = null
fun onCreate() { setContentView(...)
recyclerView = ....
adapter = createAdapter()
recyclerView!!.adapter = adapter!!
}

our code becomes something like

val recyclerView: RecyclerView by bindView(R.id.recycler)val adapter : Adapter by lazy {
createAdapter()
}
fun onCreate() {
setContentView(...)
reyclerview.adapter = adapter
}

The first line use a delegated property provided by https://github.com/JakeWharton/kotterknife , the second use the lazy delegated property from kotlin stdlib

Benefits :

  • you transform a nullable type in a non-nullable type
  • you get rid of mutability (val vs var)
  • you reduce the cognitive load by having the field declaration and initialisation grouped together.

--

--