Home > Software engineering >  How to call an abstract method from a Class parameter in Kotlin?
How to call an abstract method from a Class parameter in Kotlin?

Time:11-14

Aim

Have a function Book, which takes one of three Letter classes as argument myClass and then calls 'genericMethod()' from the abstract class which Letter*() has inherited.

Issue

If I try Book(LetterA()).read() I get the following error:

Type mismatch. Required: Class<SampleClassArguments.Alphabet> Found: SampleClassArguments.LetterA

Does Kotlin have any way to achieve this result?

Code

    @Test
    fun readBookTest() {
        Book(LetterA()).read() /*<--error here*/
    }

    class Book(val myClass: Class<Alphabet>) {
        fun read() {
            val letterClass = myClass.getConstructor().newInstance()
            letterClass.genericMethod(myClass.name)
        }
    }
    
    class LetterA(): Alphabet()
    class LetterB(): Alphabet()
    class LetterC(): Alphabet()

    abstract class Alphabet {
        fun genericMethod(className: String) {
            println("The class is: $className")
        }
    }

CodePudding user response:

You need to define the Class type as covariant with the out keyword so any of the child classes is an acceptable argument:

class Book(val myClass: Class<out Alphabet>)

And when you use it, you need to pass the actual Class, not an instance of the class. You can get the Class by calling ::class.java on the name of the class:

@Test
fun readBookTest() {
    Book(LetterA::class.java).read()
}
  • Related