2

Is it possible in Kotlin to directly access a public backing-field declared in a Java class, if that class happens to have the corresponding getter for the field? For example, JDK's java.awt.Dimension has the fields width and height, which are public, but also there are getWidth() and getHeight() methods (although they return doubles instead of ints, so they are not strictly 'corresponding' getters). Here is a sample code:

fun obtainWidth(): Int {
    val size = Dimension(1, 2)
    return size.width
}

The Java bytecode clearly shows the method getWidth() being called, followed by a double-to-int conversion:

  public final static obtainWidth()I
   L0
    NEW java/awt/Dimension
    DUP
    ICONST_1
    ICONST_2
    INVOKESPECIAL java/awt/Dimension.<init> (II)V
    ASTORE 0
   L1
    ALOAD 0
    INVOKEVIRTUAL java/awt/Dimension.getWidth ()D
    D2I
    IRETURN

Interestingly, if I replace width with getWidth(), then code does not compile, requiring explicit conversion.

I use Kotlin v1.3.61

ysakhno
  • 834
  • 1
  • 7
  • 17

0 Answers0