What is Kotlin Backing Field? & Field vs Property

0
719
Kotlin Backing Field
Kotlin Backing Field
Say Hi! and Follow

As an Android application developer, I have been using Java since start. And in Java there is no such thing as Backing Fields. I was introduced to this concept while learning Kotlin.

Backing field is an autogenerated field for any property which can only be used inside the accessors(getter or setter) and will be present only if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier. This backing field is used to avoid the recursive call of an accessor which ultimately prevents the StackOverflowError.

Backing field is generated only if a property uses the default implementation of getter/setter. If you see the following code with perspective of Java. It looks correct. However in Kotlin it’ll throw StackOverFlow.

In Kotlin the above code snippet will throw StackOverflow because when we access or set property firstName or lastName the default accessor will be called. So in Kotlin user.firstName = “value” is same as Java’s user.setFirstName(“value”).

Am sure you are confused with backing field term while learning Kotlin. I had spent time on this already and this article will help you with that. If you are a C++/Java programmer then you know the concepts of variables, which you can create in a class or outside a class. In OOPs, naming is different. As a C++ programmer, there is no difference between variables outside class or inside the class. For me, the class is a way of encapsulation.

So when set(value) {firstName = “value”} is called, then a recursive call happens and compiler throws a StackOverflow exception because we are calling setter inside the setter.
Solution to this problem is to user backing fields. In Kotlin a backing field can be accessed using field keyword inside accessors. Take a look at corrected code snippet below.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 25,221 other subscribers

Leave a Reply