0Pricing
Kotlin Academy · Lesson

with

Group operations.

with is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The with Function

with is a scope function that takes an object as an argument (not as a receiver of a call) and runs a block with that object as this. It returns the lambda result.

Basic with Usage

You pass the object to with and access its members directly inside the block.

fun main() {
    val name = "Kotlin"
    val description = with(name) {
        "$this has $length characters"
    }
    println(description)
}

Grouping Multiple Operations

with shines when you need to call several methods or read several properties on the same object. It avoids repeating the object name.

fun main() {
    val sb = StringBuilder()
    with(sb) {
        append("Line 1\n")
        append("Line 2\n")
        append("Line 3")
    }
    println(sb)
}

with Uses this

Like run and apply, with exposes the object as this, so member access needs no prefix.

data class Rectangle(val width: Int, val height: Int)

fun main() {
    val rect = Rectangle(4, 5)
    val area = with(rect) {
        width * height
    }
    println("Area: $area")
}

with Returns the Lambda Result

The value of the last expression in the block becomes the result of with, just like run.

fun main() {
    val list = listOf(1, 2, 3, 4, 5)
    val summary = with(list) {
        "Size=$size, First=${first()}, Last=${last()}"
    }
    println(summary)
}

with vs run

with(obj) { ... } and obj.run { ... } do almost the same thing. The difference is syntax:

  • run is an extension called on the object, so it works nicely with safe calls.
  • with takes the object as an argument and reads naturally as "with this object, do...".
fun main() {
    val s = "data"
    val a = with(s) { uppercase() }
    val b = s.run { uppercase() }
    println("$a $b")
}

with Is Not for Nullables

Because the object is passed as an argument, with does not combine cleanly with the safe-call operator. For nullable receivers prefer obj?.run { } or obj?.let { }.

fun main() {
    val name: String? = "Eve"
    name?.run { println("Hello $this") }
    println("with is awkward for nullables")
}

Reading and Computing Together

A common pattern is to read several properties and compute a single result, all inside one readable block.

data class Order(val items: Int, val pricePerItem: Int)

fun main() {
    val order = Order(3, 20)
    val total = with(order) {
        items * pricePerItem
    }
    println("Total: $total")
}

Building Strings with with

Combined with buildString or StringBuilder, with creates clean, prefix-free building code.

fun main() {
    val report = StringBuilder()
    with(report) {
        appendLine("Report")
        appendLine("======")
        appendLine("All good")
    }
    print(report)
}

with on a Collection

You can call many collection functions on the same list without repeating its name.

fun main() {
    val numbers = listOf(10, 20, 30)
    with(numbers) {
        println("Sum: ${sum()}")
        println("Max: ${max()}")
        println("Average: ${average()}")
    }
}

When to Use with

Choose with when you have a non-null object and want to perform a group of operations on it, optionally returning a result. It signals "I am working with this object for a while".

Quick Check

How does with receive its object?

Recap

with groups operations on a single non-null object passed as an argument, exposes it as this, and returns the lambda result. It is like run but with argument syntax. Next you will learn how to choose the right scope function for each situation.

Frequently asked questions

Is the “with” lesson free?

Yes — the full text of “with” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “with”?

Group operations. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “with” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. let and run
  2. apply and also
  3. with
  4. Choosing the Right One
← Back to Kotlin Academy