Kotlin run function


Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.

Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.
There are a few scope functions
To keep this article short and to the point, we will talk only about run in this article and all the use cases around it.


run has two variants.

One is an extension function to Template class which takes a lambda (higher-order function) as a parameter, apply contract on it and ultimately return the execution of the lambda we passed as a parameter to it.

Second is not an extension function to Template class but a normal extension function that takes a higher-order function as parameters, applies the operations and return the lambda expression or results. The return type can also be void.

  

/**
* 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.

The contract is nothing but a contract applied to the passed lambda as a parameter.
  
/**
* 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) { }
This is exactly the same contract as to any other scope function. This superimposes some conditions on the lambda we passed as a parameter to the run function. What conditions it superimposed, we need to check the parameter of the contract

And what contract applied in the run functions ?

  
/**
* Specifies that the function parameter [lambda] is invoked in place.
*
* This contract specifies that:
* 1. the function [lambda] can only be invoked during the call of the owner function,
* and it won't be invoked after that owner function call is completed;
* 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter,
* see the [InvocationKind] enum for possible values.
*
* A function declaring the `callsInPlace` effect must be _inline_.
*
*/
/* @sample samples.contracts.callsInPlaceAtMostOnceContract
* @sample samples.contracts.callsInPlaceAtLeastOnceContract
* @sample samples.contracts.callsInPlaceExactlyOnceContract
* @sample samples.contracts.callsInPlaceUnknownContract
*/
@ContractsDsl public fun callsInPlace(lambda: Function, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace
It superimposes 2 conditions
  1. The lambda will be invoked only during owner function call and it won't be called once the owner function is completed.
  2. The number of times this lambda function will be invoked (which is exactly once in our case) which is an enum.
The above conditions are clear from there definition itself.

So basically, run function will be

  • called only during the owner function will be called.
  • called ONLY ONCE.
  • called on the calling object in case of Template class extension and on the context in case of non Template class extension.
  • and will return the expression returned by the lambda passed to the run function.

Now let's look at the use cases

run which is an extension to Template class is similar to let but the only difference is in let we get a reference as it whereas in run, the reference is this.

The best use case of this run function is to avoid the null check. run function used with ?. ensures the execution only if the expression is non-null. You can read about the null safety in the Kotlin here.
  
class Employee {
var firstName: String? = null
var age: Int = 0
}

val employee: Employee? = Employee()
employee?.firstName = "Suneet"
employee?.age = 27

employee?.run {
println(age)
}

Please note that we can even point to the calling object by this but we can't use a named parameter in run.
  
employee?.run {
println(this.age)
}
run function which is not an extension to Template class is similar to with but the only difference is in with we can pass the object as a param, here we can't pass it but this will only be executed on the outer (function/class/context) scope.

run lets us execute a block of several statements where an expression is required.
This is like defining our block and the variables which will be defined in that block will not be present outside.
  
val alphaNumeric = run {
val digits = "0-9"
val aplhabets = "A-Za-z"

Regex("[$digits$aplhabets]+")
}


for (match in alphaNumeric.findAll("+1234 -FFFF I-am?-a!string?!")) {
println(match.value)
}


//this will print
1234
FFFF
I
am
a
string


Things to keep in mind about run,

  1. run has two variants, one is an extension function to Template class and another one is not an extension function to Template class.
  2. run uses the context as this and we can not use a named parameter instead of this.
  3. run return the last expression of the lambda passed which can also be void.


Reference: Kotlin docs