Kotlin also function

This post was originally posted at https://agrawalsuneet.github.io/blogs/kotlin-also-function/ and reposted on Medium on 5th June 2021.
/**
* Calls the specified function [block]
* with `this` value as its argument
* and returns `this` value.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}

This clarifies a few things

  1. The return type of the also function is nothing but the same calling object.
  2. Since its an extension function to the Template class, it can be called on any object.

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 also function

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