1

For example, here is a Java class

public class Thing {
    ...
    public int thing;
    public int getThing() { return thing; }
    public void 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?

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
DEDZTBH
  • 186
  • 1
  • 1
  • 10
  • 1
    Consider just using getters and setters when you don't really need direct access (mostly never): https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors – Ivan Dimitrov Oct 04 '20 at 09:29

2 Answers2

2

I'm not sure the byte code you're looking at is giving you you the full explanation.

I modified your test class to give getThing() and setThing() different behaviour to the underlying field:

public class Thing {
    public int thing;
    public int getThing() { return thing + 1; }
    public void setThing(int t) { thing = 0; }
}

Then when running this Kotlin code:

fun main() {
    val t = Thing()
    t.thing = 1
    println(t.thing)
    println(t.getThing())

    t.setThing(1)
    println(t.thing)
    println(t.getThing())
}

I get:

1
2
0
1

Which indicates that t.thing is in fact getting and setting the field directly.

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • 1
    Turns out Intellij's Kotlin bytecode is a bit misleading, in the actual .class file it is indeed direct field access. – DEDZTBH Oct 05 '20 at 03:13
0

You can access Java fields directly from the Kotlin code. So, if you don't have a getter, you can still access t.thing.

But I don't think it's possible to access the field when you have a getter. If you cannot edit the Java code but still want to access the field directly (to avoid side-effects in a getter or something), you can do it using another Java class. This way you can manage access to the field.

public class AnotherThing {
    ...
    public Thing thing;
    public getField() { return thing.thing; }
}
Konstantin Raspopov
  • 1,565
  • 1
  • 14
  • 20