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

Time:12-27

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?

CodePudding user response:

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
}

CodePudding user response:

For your usecase you might not need to make any class at all. Just attach the function to an object. For example:

object MyObject {
    fun showSomething() {
        println("Hello World")
    }
}

This declaration can be put outside of classes on its own.

Then you can call MyObject.showSomething() wherever you like.

And you can actually also just define the function outside of any classes or objects like

fun showSomething() {
    println("Hello World")
}

and then use showSomething() wherever you like but maybe it's kinda bad practice to do it like that.

  • Related