I am very new to Kotlin. I have consulted so many tutorials today for the implementation of an abstract class in Kotlin. I want to have a class that wraps a few functions without the need to instantiate the class itself. Therefore, I figured an abstract class is the perfect candidate for this. However, it seems that I cannot call the member functions inside an abstract class even if I add the ‘open’ modifier to the functions. Example:
abstract class MyAbstractClass {
open fun showSomething() {
println("Hello World")
}
}
fun main() {
MyAbstractClass.showSomething() //Shows unresolved reference
}
Please note that I am using Android Studio 2021.1.1.Beta.4 for now. Am I understanding abstract classes wrong ? Please explain, thanks in advance!
>Solution :
It sounds like you want a companion object and put the function in there. The open keyword only opens up the function to be overridden. All classes in Kotlin are final by default so they can’t be extended unless you open them up.
abstract class MyAbstractClass {
companion object {
fun showSomething() {
println("Hello World")
}
}
}
Now you can use it without instantiate anything:
fun main() {
MyAbstractClass.showSomething() //Hello World
}