Cross references in type parameters

Kotlin doesn’t have raw types, you cannot just drop the type parameters.

One option similar to raw types is to use star projections:

abstract class Element<S : Snapshot<*>> { /* ... */ }
abstract class Snapshot<E : Element<*>> { /* ... */ }

But you won’t be able to normally work with the type parameters generic members.


Another option is to introduce mutual constraints like this:

abstract class Element<E : Element<E, S>, S : Snapshot<S, E>>() { /* ... */ }
abstract class Snapshot<S : Snapshot<S, E>, E : Element<E, S>>() { /* ... */ }

With this definition, you can be sure that if you define SomeSnapshot: Snapshot<SomeSnapshot, SomeElement>, the type SomeElement is aware of SomeSnapshot, because it is constrained to be derived from Element<SomeElement, SomeSnapshot>.

Then the implementation would be:

class SomeElement : Element<SomeElement, SomeSnapshot>() { /* ... */ }
class SomeSnapshot : Snapshot<SomeSnapshot, SomeElement>() { /* ... */ }

Leave a Comment