1

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
}
2
  • What does your interface look like? Which part of the code exactly do you want to make generic? Commented Apr 12, 2018 at 5:04
  • The check method I want to make it take a Array<String> type, but it's throwing me a compile error Commented Apr 12, 2018 at 5:07

1 Answer 1

3

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

1 Comment

If I have to keep the type parameter for a generic function why can I do override fun <String> check(classData: ClassData, value: String): Boolean { //TODO }

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.