Plee
Plee

Reputation: 591

Array as Generic Type in Kotlin

I am getting an error asking for member declaration and I have no idea why. I have been trying to look things up but can't seem to find an answer to why this is invalid. I can do val listOfArr = ArrayList<Array<String>>() just fine. Why does this not work?

class Implements: IPatternCheck {

    override fun <Array<String>> check(classData: ClassData, value: Array<String>): Boolean {
       return true
    }
}

This is my interface

interface IPatternCheck {
    fun<T> check(classData: ClassData, value: T): Boolean
}

Upvotes: 1

Views: 834

Answers (1)

zsmb13
zsmb13

Reputation: 89668

If your interface declares a function with a type parameter, you have to keep that type parameter intact when you override it - so you'd have to create this override for it in your class:

override fun <T> check(classData: ClassData, value: T): Boolean {
    // TODO
}

To make it take a specific type, you should make your interface generic instead of just the function inside it, and implement the interface with the specific type passed as the type parameter:

interface IPatternCheck<T>  {
    fun check(classData: ClassData, value: T): Boolean
}

class Implements: IPatternCheck<Array<String>> {
    override fun check(classData: ClassData, value: Array<String>): Boolean {
        // TODO
    }
}

Edit, answering the question in the comment below. If you do this:

override fun <String> check(classData: ClassData, value: String): Boolean {
    // TODO
}

... all you're doing is just renaming the T type parameter to String (rather confusingly). You're not actually using the kotlin.String class that stores a sequence of characters.

For example, you can still call an instance of Implements with any second parameter, it won't be restricted to a kotlin.String. It's still a generic function.

val implements = Implements()
implements.check(ClassData(), "foo")
implements.check(ClassData(), 25)

Also, you can't access any kotlin.String functions on the parameter:

override fun <String> check(classData: ClassData, value: String): Boolean {
    value.length // Unresolved reference: length
}

Upvotes: 3

Related Questions