.apply { } in Kotlin

Clean code. Available in Kotlin.

We've probably all written code like this:

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = PodcastEpisodeAdapter()

However, Kotlin simplifies this with the apply keyword:

        recyclerView.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = PodcastEpisodeAdapter()
        }

Did you catch that? With apply we can write code (such as layoutManager, adapter) as if it were preceding each line recyclerView. Neat!

apply is similar to let{}.

Omit Data Type

More Tutorials

Build a Ridesharing Android App - Part 1

Getting started is sometimes the hardest part.

setOnClickListener

Add a click listener in Kotlin.

Android Login Layout

Let users sign in.