https://kotlinlang.org logo
#announcements
Title
# announcements
j

jbnizet

10/11/2019, 10:28 AM
I expected to find a private setter in the byte code when compiling the following class, but there is none. Is that documented behavior, or is it an undocumented optimization. Doesn’t that optimization break reflection-based code that expects the setter to be there?
Copy code
class Dog {
     var frightenedCats = 0
         private set

     fun frightenCat() {
         frightenedCats++
     }
 }
Here’s the output (I just omitted the constructor) when decompiling the bytecode with `javap -p -c`:
Copy code
private int frightenedCats;

  public final int getFrightenedCats();
    Code:
       0: aload_0
       1: getfield      #10                 // Field frightenedCats:I
       4: ireturn

  public final void frightenCat();
    Code:
       0: aload_0
       1: dup
       2: getfield      #10                 // Field frightenedCats:I
       5: dup
       6: istore_1
       7: iconst_1
       8: iadd
       9: putfield      #10                 // Field frightenedCats:I
      12: return
Note: I’m absolutely fine with that optimization. Just curious about it.
j

Jonathan Shore

10/11/2019, 2:54 PM
Since the setter is private there is no need for it to create a setFrightenedCat(Int). The get and set methods would be more for java compatibility and eternal object property reference. I like the way this was optimized. Avoiding a function call is a significant performance improvement generally.
2 Views