Kotlin Tip #20: Use the ALSO Function to Perform Side Effect Operations— 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readFeb 29, 2024

Twitter | LinkedIn | YouTube | Instagram
Tip #19:
Use the APPLY Function to Configure Complex Objects

Today, we will talk about the last of the five Kotlin scope functions, the ALSO function.

The ALSO is particularly useful for executing operations that should not interfere with the main object’s state or for adding logging and other side effects.

In this example, also is used to log the details of the File object and then save it right after its initialization with apply. The use of it within the also block refers to the File object, allowing direct access to its properties. The beauty of also lies in its simplicity and power to maintain code readability while offering the flexibility to add meaningful side operations.

Furthermore, also’s ability to return the original object makes it a perfect tool for chaining multiple operations, where each operation is separate, and keeping the core business logic clean and independent.

Regardless of the side-operation you're performing, the also function exemplifies Kotlin’s commitment to concise, readable, and expressive code.

I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #21: Use Sealed Classes to Improve Error Handling

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--