Implementation suggestion for the upcoming data-class inheritance


#1

This is an implementation idea/proposal for the upcoming data-class inheritance in Kotlin 1.1

When implementing data-class inheritance contained in a sealed class, consider adding an internal ordinal like in Java’s enum implementation, so that when expressions can make use of standardlookupswitch/tableswitch instructions instead of using instanceof if-else chains. This may greatly improve performance when data-class inheritance is used like ADTs. Only doing this for data-class inheritance in sealed classes guarantees the safety of this implementation.

After further research this also holds true for non data-classes given the context of inheritance in a sealed class, which makes this a more general optimization.

The limitation of this optimization is that there are only some when expressions which can be optimized this way (only checking for types, nothing else), as a lookupswitch/tableswitch instruction only works for enum-esque checks, not complex conditionals.

Example code:

sealed class A {
    data class B(example: String) : A
    data class C(example: String) : A
    data class D(example: String) : A
}

#2

We do plan to implement this optimization. However, it’s not in any way tied to data classes or the language changes in 1.1; it applies to all sealed classes and can be implemented in the 1.0.x timeframe.


#3

As my posts reflects I came to the same conclusion after some research. Nice to know this is already planned. Thanks for the heads up.