cluster1
cluster1

Reputation: 5664

Understanding the syntax of Getters/Setters in Kotlin

Regarding a code example like this one:

var someProperty: String = "defaultValue"
    get() = field
    set(value) { field = value }

Is it mandatory to write the get-/set-methods right below the attribute-declaration? It won't work if I have something in between attribute-declaration and get/set-definition?

Is the nesting just for better reading or is it part of the syntax?

Upvotes: 1

Views: 102

Answers (1)

Naor Tedgi
Naor Tedgi

Reputation: 5699

because you're using var and its public all this part

  get() = field
  set(value) { field = value }

is redundant and the Kotlin compiler should alert about it.

also, you can see that when you compile your code to kotlin byte code with or without the setter and getter the outcome is the same

@Metadata(
   mv = {1, 4, 1},
   bv = {1, 0, 3},
   k = 1,
   d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u000e\n\u0002\b\u0005\u0018\u00002\u00020\u0001B\u0005¢\u0006\u0002\u0010\u0002R\u001a\u0010\u0003\u001a\u00020\u0004X\u0086\u000e¢\u0006\u000e\n\u0000\u001a\u0004\b\u0005\u0010\u0006\"\u0004\b\u0007\u0010\b¨\u0006\t"},
   d2 = {"Lorg/example/Fo;", "", "()V", "someProperty", "", "getSomeProperty", "()Ljava/lang/String;", "setSomeProperty", "(Ljava/lang/String;)V", "stream"}
)
public final class Fo {
   @NotNull
   private String someProperty = "defaultValue";

   @NotNull
   public final String getSomeProperty() {
      return this.someProperty;
   }

   public final void setSomeProperty(@NotNull String var1) {
      Intrinsics.checkNotNullParameter(var1, "<set-?>");
      this.someProperty = var1;
   }
}

and last for the order question, The full syntax for declaring a property is

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]

so you cant add anything in between the declaration parts

Upvotes: 1

Related Questions