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

112
Visualizações
Higher Order Function as Enum paramter

I want to use a higher order function as enum parameter. But this doesn't work. I have the following declaration:

enum class Enum(val someValue: Int, val someMethod: () -> Unit)
{
    FIRST_VALUE(0, {method0()}),
    SECOND_VALUE(1, {method1()})

    fun method0() {

    }

    fun method1() {

    }
}

But method0() and method1() cannot be found. Error is Unresolved reference: method0.

Is it somehow possible to realize this with an enum?

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

0

The type of the methods inside Enum is Enum.() -> Unit, not () -> Unit. It will work if you change the parameter type.

Note that you can also use a method reference with Enum::method0, instead of creating a new lambda. It's a bit more readable.

enum class Enum(val someValue: Int, val someMethod: Enum.() -> Unit) {
    FIRST_VALUE(0, Enum::method0), // Using a method reference
    SECOND_VALUE(1, {method1()})

    fun method0() {

    }

    fun method1() {

    }
}
over 4 years ago · Santiago Trujillo Relatório

0

Yes it's possible, but you need to move functions method0 and method1 out of the Enum class:

enum class Enum(val someValue: Int, val someMethod: () -> Unit)
{
    FIRST_VALUE(0, ::method0), // pass reference to the function
    SECOND_VALUE(1, { method1() }); // pass lambda and call `method1()` function in it
}

fun method0() {

}

fun method1() {

}

You can pass reference to a function as a lambda argument as demonstrated in FIRST_VALUE example, or lambda and call a function in it - demonstrated in SECOND_VALUE example.

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