Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove getters and setters from kotlin code

For this code

class Foo {
    var name: String? = null
}

kotlin compiler generates:

private String name;
public final String getName() { ... }
public final void setName(String name) { ... }

Even if property name doesn't have custom getter or setter. It's possible to remove redundant get and set methods using @JvmField annotation. So this code

class Foo {
    @JvmField
    var name: String? = null
}

generates only one field without additional methods.

public String name;

But is there any way to make kotlin compiler not generate getters and setters for all properties in entire project? No matter if it has annotation or not. Maybe some experimental compiler flags?

I want it because I have android instrumentation tests written on kotlin. Test apk exceeds 65k method count limit. About 2k of methods is generated getters/setters. I cannot use proguard or multidex due to some bugs in android build system. So removing kotlin synthetic methods will help me a lot.

like image 965
nnesterov Avatar asked Nov 22 '17 23:11

nnesterov


Video Answer


1 Answers

You can simply declare your properties as private, they won’t have getters and setters generated then.

class Foo {
  private val foo: String = "foo"
}

This will generate the following class:

→ javap -classpath build/classes/kotlin/test -p test.Foo
Compiled from "Foo.kt"
public final class test.Foo {
  private final java.lang.String foo;
  public test.Foo();
}
like image 71
Bombe Avatar answered Oct 17 '22 20:10

Bombe