I am a Swift developer learning Kotlin since last ...
# getting-started
r
I am a Swift developer learning Kotlin since last 2 days by following https://play.kotlinlang.org. I have doubt related to lambdas. Question - In Swift, we have a similar concept like lambda called as closure. But, they are distinctly differentiated when passing them into function arguments by marking them as
@escaping
or
@non-escaping
which denotes if they will be executed asynchronously or synchronously respectively. How do we differentiate between asynchronous or synchronous lambdas in Kotlin?
s
I haven't used swift but maybe you could achieve something similar with contracts? A contract lets you specify that a lambda argument will be called in place, e.g.
Copy code
public inline fun <R> run(block: () -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block()
}
Inline functions will help too, because an inline lambda has to be non-escaping
h
escaping and nonescaping have nothing to do with async. It is often used by async callbacks, but the real reason is memory usage/cleanup, non-escaping closure parameters are not available after the function returns, the reference is cleaned, by marking the closure parameter with
@escaping
its reference still exists after the method returns. Swift uses arc with an explicit memory manager, while Kotlin does not have such a strict memory model and uses a garbage collector. For
async
functions, like Swift 5.5, you use
suspend
in Kotlin.
☝🏾 2
☝️ 2
e
there is somewhat of a similar concept, though: lambdas arguments to
inline
functions never escape, because they are not actually represented by lambda objects, and all usages are inlined (except for arguments marked `crossinline`/`noinline`)
👍🏾 1
👍 1