Implementation suggestion for the upcoming data-class inheritance

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 standard lookupswitch/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
}

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.

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.

I found interesting bug in sealed+data class combination through inheritance:

sealed class A(val a: String) {
    data class B(val b: String) : A("hello")
}

fun main() {
    val sth = A.B("world")
    println("${sth.a} ${sth.b}")
    println(sth) // where is "a=hello" ?
}

it yields:

hello world
B(b=world)

apparently, autogenerated toString() ain’t aware of property inherited from sealed superclass

This is no bug. This is the intended behavior. Although it’s not perfect there are many problems with auto generating those methods for inherited properties, so they are ignored. If you want more info you can just search this forum, there are a few threads about it if I remember correctly.
This might change in the future but the current behavior is that only propreties in the primary constructor are used to generate toString, equals, etc.