fun MutableList<out Any>.reorder(a: Int, b: Int){
val first = this[a]
val second = this[b]
removeAt(a)
add(a, second)
removeAt(b)
add(b, first)
}
The add functions give compile errors, saying Required: Nothing, Found: Any.
When I change <out Any> to <Any>, the compile errors go away but now the function is unaccessible to anything that extends Any.
Is there a way of fixing this?
CodePudding user response:
Since you need to take things out of the list and put things into the list, neither in or out works. The type argument needs to be invariant.
To make this work on all lists, you should add a generic parameter:
fun <T> MutableList<T>.reorder(a: Int, b: Int){
val first = this[a]
val second = this[b]
this[a] = second
this[b] = first
}
CodePudding user response:
What about:
fun <T> MutableList<T>.reorder(a: Int, b: Int) {
val first = this[a]
val second = this[b]
removeAt(a)
add(a, second)
removeAt(b)
add(b, first)
}
Update
Sorry duplicate haven't seen the answer a minute before
