Kotlin equivalent for Swift's `@autoclosure`

Viewed 421

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: ""))
1 Answers

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.

Related