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

365
Views
Kotlin equivalent for Swift's `@autoclosure`

I'm wondering if there's an equivalent to Swift's @autoclosure feature

Essentially, I want to be able to create an argument in a function or constructor/initializer that can take another function that takes parameters, and execute it:

class Step(handler: () -> Unit) {

    init {
        handler()
    }

}

Step(aFunctionThatTakesParameters(parameter: String)) // <- Is there a way to get something like this working?

For reference, the equivalent code in Swift looks like this:

struct Step {

    init(_ handler: @autoclosure () -> Void) {
        handler()
    }

}

Step(aFunctionThatTakesParameters(parameter: ""))
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I pulled open the Swift documentation for Auto closures at the link: https://docs.swift.org/swift-book/LanguageGuide/Closures.html#ID543

That references this code:

var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
// Prints "5"

let customerProvider = { customersInLine.remove(at: 0) }
print(customersInLine.count)
// Prints "5"

print("Now serving \(customerProvider())!")
// Prints "Now serving Chris!"
print(customersInLine.count)
// Prints "4"

I then wrote the following to translate from Swift to Kotlin:

val customersInLine = mutableListOf("Chris", "Alex", "Ema", "Barry", "Daniella")
println(customersInLine.size)
// Prints "5"

val customerProvider = { customersInLine.removeAt(0) }
println(customersInLine.size)
// Prints "5"

println("Now serving ${customerProvider()}!")
// Prints "Now serving Chris!"
println(customersInLine.size)
// Prints "4"

While this doesn't seem to give the expected output you are looking for, you could do something more along the lines of...

class Step (handler: () -> Unit) {
    init {
        handler()
    }
}

fun myParamFunction(a: String, b: String) {
    a + b
}

Step {
   myParamFunction("Hello ", "there") 
}

In this case, the best Kotlin can do is take a pure lambda function, and internally call a function that has been given parameters to be called.

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!