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

Chris Miller

12/04/2019, 10:28 AM
I'm assuming based on the "Future improvements" section on this KEEP https://github.com/Kotlin/KEEP/blob/master/proposals/data-class-inheritance.md that the following isn't possible? Any suggestions for the most elegant alternative?
Copy code
sealed class TimedEvent(val eventTime: Long)
data class FxRateEvent(val currency: String, val rate: Double, eventTime: Long) : TimedEvent(eventTime)
a

adimit

12/04/2019, 10:30 AM
Try
Copy code
sealed class A(open val f: String)
data class B(val foo: String, override val f: String): A(f)
c

Chris Miller

12/04/2019, 10:34 AM
Ah nice, thanks!
Hmm, doesn't work for my use case unfortunately:
Copy code
org.apache.avro.AvroRuntimeException: avro.shaded.com.google.common.util.concurrent.UncheckedExecutionException: org.apache.avro.AvroTypeException:
class pojo.TimedEvent contains two fields named: private long pojo.TimedEvent.eventTime
a

adimit

12/04/2019, 6:43 PM
That's weird, we've been using this in production a lot. Maybe some problem with reflection in Javaland? I don't know what these value types compile to.
c

Chris Miller

12/05/2019, 10:06 AM
Well looking at the bytecode, looks like the "override val" creates a new field, getter and setter, so the field is duplicated rather than reused. I've changed to using normal (non-data) classes instead which behaves as expected
a

adimit

12/05/2019, 10:56 AM
You'll have to implement
.equals
and
.hashCode
though 😕 I'm surprised the byte code is this simple.
c

Chris Miller

12/05/2019, 12:46 PM
I often end up having to implement
.equals
and
.hashCode
on data classes anyway (or just not use them) because I tend to only want to test for equality based on a single ID field rather than all of them (which in some cases can end up quite expensive)
6 Views