Marc Knaup
12/27/2020, 4:32 PMinterface WithCompanion<T : Any>
fun <T : Any> companionOf(instance: WithCompanion<T>): T =
TODO() // intrinsic
Now the following would be possible:
interface FooInterface: WithCompanion<Any>
fun bar(foo: FooInterface) {
val companion: Any = companionOf(foo)
// …
}
Which would be very useful for a frequent pattern, where you have instances of something that has a shared definition across all instances:
// Types implement `Event` must also have their companion implement `Event.Type`
interface Event : WithCompanion<Event.Type> {
interface Type {
val id: String
}
}
// We can get the companion of an Event instance without reflection.
val Event.type get() = companionOf(this)
// Example
class SunriseEvent : Event {
companion object : Event.Type {
override val id = "sunrise"
}
}
fun storeEvent(event: Event) {
// Not possible like this at the moment without manually adding `type` to every single class implementing `Event`
val typeId = event.type.id
// …
}
Ruckus
12/27/2020, 5:11 PMEvent
interface.Marc Knaup
12/27/2020, 5:18 PMEvent
implementation exists and implements Event.Type
. So you can use SunriseEvent.id
for example (and other functionality). You can also pass SunriseEvent
around as an object, e.g. loadEventsOfType(SunriseEvent)
.
b) If I merely add type: Type
as a property to the interface, every single of my dozens of classes must repeat the following:
val type: Type get() = Companion.type
Instead of repeating myself over and over again I would like to simply state the relation between a class’s instance and its companion explicitly.
There’s a relation between a class and its companion already. We simply cannot access it programmatically without reflection nor with static type safety.Hanno
12/27/2020, 5:27 PMDominaezzz
12/27/2020, 5:30 PM@AnnotatedObject
or similar; kotlinx.serialization uses it.Marc Knaup
12/27/2020, 5:32 PMKotlin/Native can do this. Maybe it can be made MPP. iirc the annotation to achieve this isI can’t find any info about this. Do you have any link?or similar; kotlinx.serialization uses it.@AnnotatedObject
Dominaezzz
12/27/2020, 5:33 PMMarc Knaup
12/27/2020, 5:34 PMHanno
12/28/2020, 11:49 AM