Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda