Share common properties between Kotlin classes

Viewed 507

I have 2 (data) classes that almost share the same properties:

data class Foo(
    val id: FooId,
    val name: String,
    ... 10+ properties
}

data class NewFoo(
    val name: String,
    ... 10+ properties
}

I just want some syntax sugar magic here: not to repeat 10+ properties. I can make a base sealed class, but you would end up writing even more text (for passing arguments to base class ctor), although you are safer from making a mistake.

Yes, I know I could use composition for this, but here I don't want to, as there might be different 'variants' of the same data.

Am I missing something or this is not possible in Kotlin?

1 Answers

You can use an abstract (or sealed) class with abstract params instead and override them in the constructor of your data class (i.e. without additional passing them into the constructor of the base class).

abstract class Base {
    // put commons parameter here

    // abstract param needs to be initialized in the constructor of data class
    abstract val name: String 

    // you can define some not-abstract params as well
    open lateinit var someOtherParam: String
}

data class Foo1(
    override val name: String,
    val id: Int,
    val someAdditionalParam1: String
) : Base()


data class Foo2(
    override val name: String,
    val someAdditionalParam2: String,
    override var someOtherParam: String
) : Base()
Related