Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't access member functions in abstract class in Kotlin? Am I understanding it wrong?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading