Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

458
Visualizações
Can't access member functions in abstract class in Kotlin? Am I understanding it wrong?

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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda