Baterka
Baterka

Reputation: 3714

Java getter vs Kotlin getter - any difference?

Lets have these two getters in Kotlin:

data class Foo(var id: String){
  val reference get() = Reference("Patient/$id")
}
data class Foo(var id: String){
  fun getReference(){ return Reference("Patient/$id") }
}

Does the first one have some performance cons? I like it more, but I am not sure if they are built into same bytecode, or the first one adds more things, because I am basically delaring new variable and not just method.

Upvotes: 0

Views: 97

Answers (1)

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

In your example, they are equivalent behind the scenes (but obviously, you need different syntax for using the property vs. the method). Specifically, Kotlin will generate a backing field if any of the accessors use the field identifier, and the autogenerated get and set accessors do use field. So in order to avoid a backing field, you need to supply your own get accessor and (in the case of a var property) a set accessor, and none of them must use field.

Whether a property has a backing field or not, reading the property turns into a method call to get() behind the scenes, and if it's a var, assigning to the property turns into a method call to set().

Note that it's possible to get into weird situations with var if your accessors are inconsistent: var foo: Int = 3; get() = 42 will always return 42 when you read it, irrespective of the initial value and whatever you might assign to it, because you will get an autogenerated backing field since you omitted the setter, and that's what the autogenerated setter will set.

Using properties instead of Java-style getter/setter methods is strongly preferred in Kotlin.

(Thanks to @AlexeyRomanov for pointing out the specific rules.)

Upvotes: 2

Related Questions