What is Kotlin Backing Field? & Field vs Property

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.

See Also  Android Chat App using Firebase Tutorial

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.

0 0 votes
Article Rating

Related articles

Mobile App Development Services

Mobile App Development - Android mobile application developer -...

15 Upbeat IDE for developing Android App

IDE for developing android Application abbreviated as Integrated development...

How to Enable WhatsApp Payment

WhatsApp Pay has finally been given regulatory approval by...

WhatsApp Payment Launch in Brazil

Facebook's WhatsApp messaging service rolled out a system across...

Case Studies

Compass Music Platform

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

NewsWeek Magazine

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

Beauty & Makeup Shop

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...
0
Would love your thoughts, please comment.x
()
x