Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!