The as operator

The preceding automatic casting is known as smart cast. The as cast operator casts whatever value it's holding in the object into a given class type:

    val tabLayout = findViewById(R.id.tabs) as TabLayout

The previous line will cast a view that has ID tabs into TabLayout. This is known as unsafe. Because what if tabs is the ID of some button or TextView. This instruction will fail and throw an exception. A better way to use it is, with the safe cast operator. So let's modify the instructions a bit. With safe cast operator it will look like the following:

    val tabLayout = findViewById(R.id.tabs) as? TabLayout    tabLayout?.setupWithViewPager(container)

The as? will return null if the view is not of type TabLayout. And Kotlin handles ...

Get Kotlin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.