Skip to content

Instantly share code, notes, and snippets.

@nsk-mironov
Last active December 25, 2017 23:27
Show Gist options
  • Save nsk-mironov/4e3c93798eee5066239c to your computer and use it in GitHub Desktop.
Save nsk-mironov/4e3c93798eee5066239c to your computer and use it in GitHub Desktop.
Delegated properties

Delegated properties is a really nice feature of Kotlin and we are using them a lot in our code base. The entire project contains more than 500 delegated properties. Unfortunatelly, each property compiles to a class with 6 extra methods. While this can be fine if you're running on JVM, this is absolutely unacceptable in case you're targeting Android.

For example, the following class produces 2 more classes, Delegate$bar$1 and Delegate$foo$1:

public class Delegate(private val values: Map<String, Any>) {
  public val bar: String by values
  public val foo: String by values
}

Here is how Delegate$bar$1 looks like (and Delegate$foo$1 is almost the same):

@KotlinSyntheticClass(abiVersion = 32, moduleName = "hello-kotlin", version = {1, 0, 0})
/* compiled from: Delegate.kt */
final class Delegate$bar$1 extends PropertyReference1 {
  public static final KProperty1 INSTANCE;

  static {
    INSTANCE = Reflection.property1(new Delegate$bar$1());
  }

  Delegate$bar$1() {
  }

  public Object get(Object obj) {
    return ((Delegate) obj).getBar();
  }

  public String getName() {
    return "bar";
  }

  public KDeclarationContainer getOwner() {
    return Reflection.getOrCreateKotlinClass(Delegate.class);
  }

  public String getSignature() {
    return "getBar()Ljava/lang/String;";
  }
}

In case you're close to 65k methods, you may want to avoid all those methods and fortunatelly, there is a compiler flag for exactly that purpose! -Dkotlin.jvm.optimize.delegated.properties=true tells the compiler that it shouldn't generate an extra class for each delegated property. Applying this flag to our project reduced the overall number of methods by more than 2.5k. Really impressive for one single flag!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment