Hello stackoverflow communtiy,
I wrote a method using generic types. And I have the strange feeling that it's a little bit to complex. On the internet I found the concept of contra variance and variance for generic types. But my attempts to do it right were unsuccessful. Is there a way to get rid of the second (redundant) generic Type K?
fun <T, K> add(item: TreeItem<K>, startParent: TreeItem<T>, levelIndices: List<Int>) where K : T {
var currentParent = startParent
for ((counter, levelIndex) in levelIndices.withIndex()) {
if (counter == levelIndices.size - 1) {
@Suppress("UNCHECKED_CAST")
currentParent.children.add(levelIndices.last(), item as TreeItem<T>)
break
}
val positionEntryController = currentParent.children[levelIndex].value
if (positionEntryController is PositionHeaderController) {
currentParent = currentParent.children[levelIndex]
} else {
throw NotImplementedError()
}
}
}
The crucial line is under @Suppress("UNCHECKED_CAST")
, where I have to cast explicitly.