How to have a class with a self type paramter as interface in kotlin

166 Views Asked by At

I have a class Element with a Self type parameter

interface Element<Self: Element<Self>> {
    val rules: Set<(Self) -> Boolean>
}

How can I now create a List with Element as type parameter because the following doesn't function of course.

val list: List<Element>

Thanks in advance

1

There are 1 best solutions below

0
DavidBarbaran On

The error that happens there is that you lack the "<*>", it should look like this:

val list: List<Element<*>>

But I would recommend that you use the MutableList according to the documentation:

List: a generic ordered collection of elements. The methods in this interface only allow read-only access to the list; read / write access is supported through the MutableList interface.

MutableList: a generic ordered collection of elements that supports adding and removing elements.

Your list should look like this:

var myList: MutableList<Element<*>> = mutableListOf<Element<*>>()