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

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

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 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