DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Writing DTOs With Java8, Lombok, and Java14+
  • Graph API for Entra ID (Azure AD) Object Management
  • A Comprehensive Guide to IAM in Object Storage

Trending

  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • A Modern Stack for Building Scalable Systems
  • Performance Optimization Techniques for Snowflake on AWS
  • Contextual AI Integration for Agile Product Teams
  1. DZone
  2. Coding
  3. Languages
  4. Examining Kotlin: also, apply, let, run, and with

Examining Kotlin: also, apply, let, run, and with

Familiarize with these undocumented intents in Kotlin to learn when and how to use the also, apply, let, run, and with functions in your code.

By 
Željko Trogrlić user avatar
Željko Trogrlić
·
Aug. 21, 17 · Tutorial
Likes (22)
Comment
Save
Tweet
Share
39.9K Views

Join the DZone community and get the full member experience.

Join For Free

One of the things that puzzled me when I started with Kotlin was why there were so many similar functions which call lambdas on some objects and return a value. After many lines of code and many lines of user group discussions, I found out that they represent a small DSL for easier monadic-style coding. An explanation of this DSL and the intent of each function are missing from the Kotlin documentation, so this article will hopefully shed some light on them. There is also a short style guide on GitHub.

also

With this function, you say “also do this with the object.” I often use it to add debugging to the call chains or to do some additional processing:

kittenRest
    .let { KittenEntity(it.name, it.cuteness) }
    .also { println(it.name) }
    .also { kittenCollection += it }
    .let { it.id }


also passes an object as a parameter and returns the same object (not the result of the lambda!):

data class Person(var name: String, var age: Int)

val person = Person("Edmund", 42)

val result = person.also { person -> person.age = 50 }

println(person)
println(result)


Outputs:

Person(name=Edmund, age=50)
Person(name=Edmund, age=50)


Or shorter, with the default it parameter:

val result = person.also { it.age = 50 }


The original object was mutated and returned as a result.

let

let is a non-monadic version of map: It accepts objects as parameters and returns the result of the lambda. Super-useful for conversions:

val person = Person("Edmund", 42)

val result = person.let { it.age * 2 }

println(person)
println(result)


Outputs:

Person(name=Edmund, age=42)
84


apply

apply is used for post-construction configuration. It is a function literal with receiver: The object is not passed as a parameter, but rather as this. An object passed in such way is called the receiver.

val parser = ParserFactory.getInstance().apply{
    setIndent(true)
    setLocale(Locale("hr", "HR"))
}


Here is a simple example:

val person = Person("Edmund", 42)

val result = person.apply { age = 50 }

println(person)
println(result)


Outputs:

Person(name=Edmund, age=50)
Person(name=Edmund, age=50)


The structure of this example is aligned with the others, but in practice, you will do something like this:

val person = Person("Edmund").apply {
    age = 50
}


run

run is another function literal with receiver. It is used with lambdas that do not return values, but rather just create some side-effects:

text?.run{
    println(text)
}


It returns value of the expression, but it shouldn’t be used.

val person = Person("Edmund", 42)

val result = person.run { age * 2 }

println(person)
println(result)


Outputs:

Person(name=Edmund, age=42)
84


with

According to Kotlin idioms, with should be used to call multiple methods on an object.

with(table) {
    clear()
    load("file.txt")
}


with returns the result of the last expression, which is confusing; you should ignore it. Note that it does not work with nullable variables.

val person = Person("Edmund", 42)

val result = with(person) { 
    age * 2 
}

println(person)
println(result)


Outputs:

Person(name=Edmund, age=42)
84


What to Use When

Here is a short overview of what each function accepts and returns:

Parameter Same Different
it also let
this apply run, with


I was not particularly happy with the decision of standard library designers putting so many similar functions in, as they represent cognitive overload when analyzing the code. However, if you strictly use them for their intended purpose, they will state your intent and make the code more readable:

  • also: additional processing on an object in a call chain
  • apply: post-construction configuration
  • let: conversion of value
  • run: execute lambdas with side-effects and no result
  • with: configure objects created somewhere else

Be careful when using these functions to avoid potential problems. Do not use with on nullable variables. Avoid nesting apply, run, and with, as you will not know the current this. For nested also and let, use a named parameter instead of it for the same reason. Avoid it in long call chains, as it is not clear what it represents.

All these functions can be replaced with let, but then information about the intent is lost. As intent is the most valuable part of this set of functions, be careful when to use which one.

Kotlin (programming language) Object (computer science)

Published at DZone with permission of Željko Trogrlić. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Writing DTOs With Java8, Lombok, and Java14+
  • Graph API for Entra ID (Azure AD) Object Management
  • A Comprehensive Guide to IAM in Object Storage

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: