What to do with Deprecated Kotlin Synthetics?

Migrating Kotlin Synthetics to ViewBinding

Ertug Sagman
Huawei Developers
2 min readDec 30, 2020

--

Hi everyone! Today I will be talking about what is Kotlin Synthetic, why it got deprecated and what to do next.

Deprecated Kotlin Synthetic

First of all, Kotlin Synthetic was a feature brought by Kotlin team in 2017. Since then, it was a nice feature to replace findViewById but it came with its disadvantages. Synthetics:

  • Were not providing null safety,
  • Could cause namespace declaration clashes,
  • Could be used with Kotlin only.

That’s why Synthetic got marked deprecated by 1.4.20 Kotlin update. Well, back to using findViewById? Not yet. We have the option to migrate our Synthetics to ViewBinding. But before, let’s have a look.

ViewBinding

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.

In most cases, view binding replaces findViewById.

As taken from official View Binding guide, View Binding simply lets developers bind their XML references easier. For example,

First we add this snippet to our build.gradle.

Then we should set our binding with the inflate() method. After that, binding represents the XML of the class and we can access our components through this variable.

Let’s say we have a TextView and a Button with ids ‘name’ and ‘button’ respectively. In our class we can access these views with binding.

So why should we use ViewBinding? ViewBinding is a good alternative for Synthetic because it:

  • has null safety and type safety,
  • will prevent namespace clashes,
  • supports both Kotlin and Java.

Conclusion

As of November 23, 2020, we are no longer suggested to use Kotlin Synthetics. So instead we should be using other technologies like ViewBinding and slowly migrate our projects from Synthetics. You have read about how to migrate Kotlin Synthetics to ViewBinding, and it should be enough to help you to migrate your projects any time soon.

--

--