Jim Clermonts
Jim Clermonts

Reputation: 2660

What is the use case for Kotlin contracts in Android development

I've been investigating Google's Architecture samples.

https://github.com/android/architecture-samples/tree/master

And what I noticed is a lot of use of contracts

For example: in TasksActivity we find this code:

private fun setupNavigationDrawer() {
    drawerLayout = (findViewById<DrawerLayout>(R.id.drawer_layout))
        .apply {
            setStatusBarBackground(R.color.colorPrimaryDark)
        }
}

and before contracts we would write it like this:

private fun setupNavigationDrawer() {
    drawerLayout = (findViewById(R.id.drawer_layout))
    drawerLayout.setStatusBarBackground(R.color.colorPrimaryDark)
}

When clicking apply we see InvocationKind.EXACTLY_ONCE which appears that this contract makes sure that the setStatusBarBackground method is only called once.

What is the practical benefit of this checking and when should it be used? Because it is more code and less readable in my opinion.

Upvotes: 1

Views: 199

Answers (1)

Tenfour04
Tenfour04

Reputation: 93629

Contracts were added in Kotlin 1.3, but apply has been around forever. The contracts are only compiler hints, and allow functions like apply to have additional use cases (like the ability to initialize a val).

apply is more commonly used for code conciseness. Your example is an edge case where it's debatable whether the code is cleaner with it. If you're calling a series of set-up functions on an object, it's more obviously helpful for clarity and conciseness.

Upvotes: 2

Related Questions