.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

Kotlin Challenge #1

Build a simple contacts manager.

Android Basic Alert Dialog Box
Basic CardView

Basic CardView

Material Design.

Rounded Corners with a Border
Rounded Button in Android Studio

Rounded Button in Android Studio

Create beautiful buttons in XML.

RecyclerView Day 3: Invoicing app

RecyclerView Day 3: Invoicing app

Built with Android Studio and Kotlin.

Build a Ridesharing Android App - Part 1

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.