Access Java field directly instead of using getter/setter

For example, here is a Java class

public class Thing {
    ...
    public int thing;
    public getThing() { return thing; }
    public setThing(int t) { thing = t; }
}

In Kotlin, if I want to access thing , I would do the following:

val t = Thing()
t.thing // get
t.thing = 42 //set

In the decompiled Kotlin bytecode, what I see is Kotlin using getter and setter:

t.getThing()
t.setThing(42)

I wonder if there is a way to directly access the field t.thing instead of using getter and setter?

I don’t think this is possible if there are getters/setters for the field. I guess you could use reflection but that would come with some performance penalties.

Just out of interst why would you want to acess a field directly?

1 Like

Actually I am just curious about this. I think maybe the getter or setter can have side effects or excessive checkings that we don’t want.

1 Like

You could maybe write a simple ThingUtils Java class that has a static method that directly accesses the field from a passed in parameter (i.e. this:

public class ThingUtils {
    public type getThing(Thing t) { return t.thing; }
}

) and then just make an extension property on the Thing class with a different name (i.e. this:

var Thing.actualThing: type 
    get { return ThingUtils.getThing(this) }
    set(value) { ThingUtils.setThing(this, value) }

If there are side-effects, then the class clearly wants them; you’d need a pretty good reason to bypass them. Performance isn’t a good reason, either: the JVM is highly likely to inline simple getters, so they’d perform the same as a direct field access anyway.

Turns out Intellij’s Kotlin bytecode is a bit misleading, I took a look at the actual .class file and these are in fact direct field access.

1 Like