avatarGabriel Shanahan

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3056

Abstract

   </div>
        </div>
    </figure></iframe></div></div></figure><p id="55a7">This would be the equivalent code in Java:</p><div id="1803"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">FullName</span> {
<span class="hljs-keyword">private</span> String firstName;
<span class="hljs-keyword">private</span> String lastName;

<span class="hljs-keyword">public</span> String <span class="hljs-title function_">getFirstName</span><span class="hljs-params">()</span> {
    <span class="hljs-keyword">return</span> firstName;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setFirstName</span><span class="hljs-params">(<span class="hljs-keyword">final</span> String newFirstName)</span> {
    firstName = newFirstName;
}

<span class="hljs-keyword">public</span> String <span class="hljs-title function_">getLastName</span><span class="hljs-params">()</span> {
    <span class="hljs-keyword">return</span> lastName;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setLastName</span><span class="hljs-params">(<span class="hljs-keyword">final</span> String newLastName)</span> {
    lastName = newLastName;
}

<span class="hljs-keyword">public</span> String <span class="hljs-title function_">getStringRepresentation</span><span class="hljs-params">()</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"First name is '"</span> 
        + firstName 
        + <span class="hljs-string">"', last name is '"</span> 
        + lastName + <span class="hljs-string">"'"</span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setStringRepresentation</span><span class="hljs-params">(String stringRepresentation)</span> {
    <span class="hljs-type">int</span> <span class="hljs-variable">spaceIdx</span> <span class="hljs-operator">=</span> stringRepresentation.indexOf(<span class="hljs-string">" "</span>);
    <span class="hljs-keyword">if</span> (spaceIdx != -<span class="hljs-number">1</span>)
    {
        firstName = stringRepresentation.substring(
            <span class="hljs-number">0</span>,
            spaceIdx
        );
        lastName = stringRepresentation.substring(spaceIdx);
    }
    <span class="hljs-keyword">else</span> {
        firstName = <span class="hljs-string">" "</span>;
        lastName = stringRepresentation;
    }
}

}</pre></div><p id="eccd">However, when a property does need a backing field, the compiler figures it out and provides it automatically. This backing field can be referenced in the accessors using the <code>field</code> identifier:</p> <figure id="ae0b"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <i

Options

frame class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2FJkqqv8ihw&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2FJkqqv8ihw&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="213f">A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the <code>field</code> identifier.</p><p id="dbee">It should be noted that initializers are (naturally) only allowed when there is a backing field. Assigning a value to a property without a backing field results in a compile-time error.</p> <figure id="175b"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2Fr7KuA8H58&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2Fr7KuA8H58&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="79b2">This approach covers the vast majority of cases, but if you want to do something that does not fit into this “implicit backing field” scheme, you can always fall back to having a <i>backing property</i>:</p> <figure id="3e2e"> <div> <div> <img class="ratio" src="http://placehold.it/16x9"> <iframe class="" src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fpl.kotl.in%2F0c8ICMISY&amp;display_name=Kotlin+Playground&amp;url=https%3A%2F%2Fpl.kotl.in%2F0c8ICMISY&amp;image=https%3A%2F%2Fplay.kotlinlang.org%2Fassets%2Fog-image.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=kotl" allowfullscreen="" frameborder="0" height="300" width="800"> </div> </div> </figure></iframe></div></div></figure><p id="53df">Go back to <a href="https://readmedium.com/accessors-68d29db0ddf1">Accessors</a>, jump to the <a href="https://readmedium.com/table-of-contents-c52573cfa291">Table of Contents</a>, or continue to <a href="https://readmedium.com/accessors-continued-a1a57a2c4e4e">Accessors, continued</a>.</p><figure id="8ecd"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*biBSB579iezsNvEQ_NMLBg.png"><figcaption><a href="https://www.etnetera.cz/prace-u-nas?utm_source=medium&amp;utm_medium=GabrielShanahan&amp;utm_campaign=KotlinPrimer&amp;utm_content=join-our-team&amp;utm_term=KotlinPrimer#pozice">Join me in Etnetera</a></figcaption></figure></article></body>

Backing Fields

Explanation of backing fields, when they are generated and how to access them inside custom accessors

— — — — — — — — — — — — — — —

THE CURRENT VERSION OF THIS ARTICLE IS PUBLISHED HERE.

— — — — — — — — — — — — — — —

Tags: #KOTLIN FEATURE

This article is part of the Kotlin Primer, an opinionated guide to the Kotlin language, which is indented to help facilitate Kotlin adoption inside Java-centric organizations. It was originally written as an organizational learning resource for Etnetera a.s. and I would like to express my sincere gratitude for their support.

It is recommended to read the Introduction before moving on. Check out the Table of Contents for all articles.

This part can appear complicated and a little confusing, but it’s actually not — the compiler takes care of everything behind the scenes, so this part is really just FYI. Basically, this section could be condensed into the sentence “if you need to access the backing field inside an accessor, use field (i.e. field = 3 or field + 5)".

However, I think it’s useful to realize that not all properties require backing fields to be generated — it all depends on the property actually needing to hold a value in memory. The property stringRepresentation in the previous lesson is an example of a property which doesn't need a backing field — it only operates on values of other properties. The Kotlin compiler detects this and doesn't generate a backing field, saving memory.

To refresh your memory, here’s the code we’re talking about:

This would be the equivalent code in Java:

class FullName {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(final String newFirstName) {
        firstName = newFirstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(final String newLastName) {
        lastName = newLastName;
    }

    public String getStringRepresentation() {
        return "First name is '" 
            + firstName 
            + "', last name is '" 
            + lastName + "'";
    }

    public void setStringRepresentation(String stringRepresentation) {
        int spaceIdx = stringRepresentation.indexOf(" ");
        if (spaceIdx != -1)
        {
            firstName = stringRepresentation.substring(
                0,
                spaceIdx
            );
            lastName = stringRepresentation.substring(spaceIdx);
        }
        else {
            firstName = " ";
            lastName = stringRepresentation;
        }
    }
}

However, when a property does need a backing field, the compiler figures it out and provides it automatically. This backing field can be referenced in the accessors using the field identifier:

A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the field identifier.

It should be noted that initializers are (naturally) only allowed when there is a backing field. Assigning a value to a property without a backing field results in a compile-time error.

This approach covers the vast majority of cases, but if you want to do something that does not fit into this “implicit backing field” scheme, you can always fall back to having a backing property:

Go back to Accessors, jump to the Table of Contents, or continue to Accessors, continued.

Join me in Etnetera
Kotlin
Java
Programming
Getters And Setters
Backing Field
Recommended from ReadMedium