Kotlin also function

Suneet Agrawal
2 min readJun 5, 2021

In continuation to my previous post where I explained about Kotlin let function and Kotlin apply function, let’s try to understand today about also function today.

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

There are a few scope functions

To keep this article short and to the point, we will talk only about also in this article and all the use cases around it.

also is used to perform some actions on the object and returns the object itself. A reference to the calling object is available inside the also function instead of the context (this).
More than functional, also can be used as grammatical where we can read as “also do the following with the object”.

To understand also function lets look at the implementation of also function first.

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

also is an extension function to Template class which takes a lambda as a parameter, apply contract on it, execute the lambda function within the scope of calling object and ultimately return the same calling object of Template class itself.

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.

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 also function. What conditions it superimposed, we need to check the parameter of the contract.

And what contract applied in the also function

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

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--