Kotlin run function

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-run-function/ and reposted on Medium on 5th June 2021.

run has two variants.

/**
* Calls the specified function [block] and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <R> run(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
/**
* Calls the specified function [block] with `this` value as its receiver and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}

This clarifies a few things

  1. The return type of the both run functions are nothing but the last expression we returned from our passed lambda parameters.
  2. Since its an extension function to the Template class as well as generic without any class, it can be called on any object with or without chaining.

Now let’s understand what is the contract.

/**
* Specifies the contract of a function.
*
* The contract description must be at the beginning of a function and have at least one effect.
*
* Only the top-level functions can have a contract for now.
*
* @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members.
*
@ContractsDsl
@ExperimentalContracts
@InlineOnly
@SinceKotlin("1.3")
@Suppress("UNUSED_PARAMETER")
public inline fun contract(builder: ContractBuilder.() -> Unit) { }

And what contract applied in the run functions?

Please continue reading at https://agrawalsuneet.github.io/blogs/kotlin-run-function/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store