Understanding how to use with in Kotlin

February 04, 2019

Kotlin has many useful tricks that makes developers lives a lot easier. For example, using apply is super useful for changing multiple properties at the same time. However, the concept of with is also useful when you plan to call an object's function multiple times.

Let's see it in action:

class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
    penDown()
    for(i in 1..4) {
        forward(100.0)
        turn(90.0)
    }
    penUp()
}