Inlined properties

I have this Kotlin code:


var visibility = false

inline var isVisible
get() = visibility
set(value) {visibility = value}

And In Java generated code I have this:

private static boolean visibility;

public static final boolean getVisibility() { return visibility; }

public static final void setVisibility(boolean var0) { visibility = var0; }

public static final boolean isVisible() { return getVisibility(); } //getter

public static final void setVisible(boolean value) { setVisibility(value); } //setter

But when I remove the inline from the var isVisible declaration the Java code changes to:

private static boolean visibility;

public static final boolean getVisibility() { return visibility; }

public static final void setVisibility(boolean var0) { visibility = var0; }

public static final boolean isVisible() { return visibility; } //direct access

public static final void setVisible(boolean value) { visibility = value; } //direct access

Why inlined properties call get/setVisibility instead of accessing the field direclty?

Please, see the comments getter, setter, direct access at the code samples above to spot what I am trying to explain.

  1. Inline means that the body of a method is copied to the place where you call the inline function.
    This means that the function does not exist at runtime.

  2. Kotlin doesn’t know fields, only properties. A property is a combination of a private field with a getter and/or setter.

  3. An inline method can be called from outside the class, and from outside the class only the getters and setters of fields are visable.

so, an inline fun must use the getters and setters.

1 Like