Kotlin with function

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

Why with is not an extension function to Template class?

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

This clarifies a few things

  1. The return type of the with function is nothing but the last expression we returned from our passed lambda parameter.
  2. Although it's not an extension function to Template class but we can pass any object as the first param to with function.

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 with function?

Please continue reading at https://agrawalsuneet.github.io/blogs/kotlin-with-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