Subscribe for notification
Categories: Android Tutorial

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.

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.


SyncSaS Technologies is specialized in creating and designing customized software. We have our own team that will be in charge of developing your softwares.

Published by

Recent Posts

Adsense Updated Dashboard

Changes in Adsense Dashboard Recently you might have seen few changes in Adsense dashboard, these…

3 weeks ago

Guide Book For Google Adsense

With my experience in working as AdSense publisher, I have written many articles, tutorials for…

3 weeks ago

How to manage Google Adsense to get High CPC

Manage Adsense for High CPC CPC (Cost per click) in simple words the CPC is…

3 weeks ago

Google Adsense Introduce page level ads

If you are already the publisher of Google Adsense account then now its time to…

3 weeks ago