I'm just fooling around with some Functional Programming techniques and tried to implement a generic drop function for a list. However it seems the types are getting shadowed. I'm wondering why I can't re-use a generic type declared.
The IDE doesn't want me to reuse the generic type
sealed class List<out A> {
fun <A> drop(n: Int): List<A> {
fun go(n: Int, l: List<A>): List<A> = when (n) {
0 -> l
else -> go(n - 1, l.tail())
}
return go(n, this)
}
}
The IDE says the following
Type mismatch.
Required:
List<A#1 (type parameter of chapter3.List.drop)>
Found:
List<A#2 (type parameter of chapter3.List)>
Is this not possible with inner local functions?
dropfunction out of the companion object, and remove the<A>type parameter from it because it's already defined inList<out A>. When you are doinggo(n, this)insidedrop,thisis referring to the companion object, not your list.<A>fromdrop. You are defining a new genericA-type that is not the same as the one inList<out A>.