0

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?

4
  • I think you should move your drop function out of the companion object, and remove the <A> type parameter from it because it's already defined in List<out A>. When you are doing go(n, this) inside drop, this is referring to the companion object, not your list. Commented Aug 8, 2021 at 15:00
  • Argh- it actually is outside of the companion object. I was trying to remove non-related functions before posting my question. Still same error though :/ Commented Aug 8, 2021 at 15:06
  • 2
    You still haven't removed the <A> from drop. You are defining a new generic A-type that is not the same as the one in List<out A>. Commented Aug 8, 2021 at 15:12
  • Thank you! This was it. ``` fun 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) } ``` Commented Aug 8, 2021 at 15:24

1 Answer 1

1

You don't need to redefine you A type again in the function, it cames from the sealed class

sealed class List<out A> {


fun 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)
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.