Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin explain me about Backing Fields

I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

like image 781
Zumry Mohamed Avatar asked Dec 06 '17 16:12

Zumry Mohamed


People also ask

What is the use of backing field?

Backing fields allow EF to read and/or write to a field rather than a property.

What's the difference between lazy and Lateinit?

Lazy initialization is one of the property Delegate-s, while late initialization requires the use of a language keyword. Lazy initialization applies only to val, and late initialization applies only to var fields. We can have a lazy field of a primitive type, but lateinit applies only to reference types.

What is the use of Lateinit in Kotlin?

The lateinit keyword allows you to avoid initializing a property when an object is constructed. If your property is referenced before being initialized, Kotlin throws an UninitializedPropertyAccessException , so be sure to initialize your property as soon as possible.

What are Kotlin's properties?

Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.


1 Answers

Consider this class

class SomeClass {
    var counter: Int = 0
        set(value) {
            if (value >= 0) field = value
        }
}

In Android Studio go to Main menu -> Tools -> Kotlin -> Show Kotlin Bytecode and click Decompile in the Kotlin bytecode panel.

What you see is the equivalent code in Java.

public final class SomeClass {
   private int counter;

   public final int getCounter() {
      return this.counter;
   }

   public final void setCounter(int value) {
      if(value >= 0) {
         this.counter = value;
      }
   }
}
like image 149
Eugen Pechanec Avatar answered Nov 15 '22 12:11

Eugen Pechanec