David Kubecka
12/12/2023, 10:23 AMlateinit var
and define setCommonProps
on the interface
• employ some reflection magic
• ...
Example:
interface Animal { val name: String }
data class Cat(override val name: String, kittens: ...)
data class Dog(override val name: String, puppies: ...)
// how to avoid repeating the name (or generally all common props) in each instantiation
val cat = Cat(name = "cat", kittens = ...)
val dog = Dog(name = "dog", puppies = ...)
Andreas Dybdahl
12/12/2023, 10:55 AMAndreas Dybdahl
12/12/2023, 11:00 AMinterface Thing {
val type: String
fun description(): String {
return "I am a thing"
}
}
interface Animal: Thing {
override val type: String get() = "Animal"
fun bark()
}
interface UnknownThing: Thing { // Use default description for unknowns.
override val type: String get() = "Unknown"
}
data class Dog(val name: String): Animal {
override fun description(): String { // Overrides default description in Thing
return "A dog is a four legged animal."
}
override fun bark() {
TODO("Not yet implemented")
}
}
David Kubecka
12/12/2023, 11:07 AMAndreas Dybdahl
12/12/2023, 11:12 AMinterface Animal { val name: String }
data class Cat(val kittens: Int): Animal {
override val name: String = "Cat"
}
data class Dog(val puppies: Int): Animal {
override val name: String = "Dog"
}
// how to avoid repeating the name (or generally all common props) in each instantiation
val cat = Cat(kittens = 7)
val dog = Dog(puppies = 10)
David Kubecka
12/12/2023, 11:19 AMAndreas Dybdahl
12/12/2023, 11:21 AMCLOVIS
12/12/2023, 1:48 PMDavid Kubecka
12/12/2023, 2:00 PMCLOVIS
12/12/2023, 2:32 PMDavid Kubecka
12/12/2023, 2:37 PMCLOVIS
12/12/2023, 2:39 PM@Serializable
data class Animal(
val name: String,
)
@Serializable
data class Cat(
val animal: Animal,
…
)
collection.save(Cat(Animal("Foo"), …))
I don't use Spring, so I can't tell you how it works there.CLOVIS
12/12/2023, 2:39 PMDavid Kubecka
12/12/2023, 2:43 PM{animal: {name: "Foo"}, <other fields>}
right?
But I want it flattened: {name: "Foo", <other fields>}
. In other words I want to achieve the same effect as with JPA's @Embedded
(on Animal in your example).CLOVIS
12/12/2023, 2:53 PMDaniel Pitts
12/12/2023, 3:47 PM@Unwrap
. Other serializable library may have similar means.