Use Kotlin’s “with()” function to access object properties with less code

Kotlin borrows an old Pascal trick! Picture of Blaise Pascal and Kotlin logo.

Suppose we have this Kotlin class:

// Kotlin

class ProgrammingLanguage(
    var name: String,
    var creator: String,
    var yearFirstAppeared: Int,
    var remarks: String,
    var isInTiobeTop20: Boolean) {
    fun display() {
        println("${name} was created by ${creator} in ${yearFirstAppeared}.")
        if (isInTiobeTop20) {
            println("This language is in the TIOBE Top 20.")

Creating an instance is pretty straightforward:

// Kotlin

val currentLanguage = ProgrammingLanguage(
    "Nikalus Wirth", 
    "My first compiled and structured language. Also my first exposure to pointers.",

When you run the code currentLanguage.display(), you get:

Pascal was created by Nikalus Wirth in 1970. My first compiled and structured language. Also my first exposure to pointers.

Suppose you want to change all the properties of currentLanguage and then display the result. If you’re used to programming in other object-oriented programming languages, you’d probably do it like this:

// Kotlin = "Miranda"
currentLanguage.creator = "David Turner"
currentLanguage.yearFirstAppeared = 1985
currentLanguage.remarks = "This was my intro to functional programming. It’s gone now, but its influence lives on in Haskell."
currentLanguage.isInTiobeTop20 = false

For the curious, here’s the output:

Miranda was created by David Turner in 1985. This was my intro to functional programming. It’s gone now, but its influence lives on in Haskell.

Now, that’s a lot of currentLanguage. You could argue that IDEs free us from a lot of repetitive typing, but it still leaves us with a lot of reading. There should be a way to make the code more concise, and luckily, the Kotlin standard library provides the with() function.

The with() function

One of the first programming languages I learned is Pascal. I cut my teeth on Apple Pascal on my Apple //e and a version of Waterloo Pascal for the ICON computers that the Ontario Ministry of Education seeded in Toronto schools.

Pascal has the with statement, which made it easier to access the various properties of a record (Pascal’s version of a struct) or in later, object-oriented versions of Pascal, an object.

Kotlin borrowed this trick and implemented it as a standard library function. Here’s an example, where I change currentLanguage so that it contains information about BASIC:

// Kotlin

with(currentLanguage) {
    name = "BASIC"
    creator = "John Kemeny and Thomas Kurtz"
    yearFirstAppeared = 1964
    remarks = "My first programming language. It came built-in on a lot of ‘home computers’ in the 1980s."
    isInTiobeTop20 = false

This time, when you run the code currentLanguage.display(), you get…

BASIC was created by John Kemeny and Thomas Kurtz in 1964. My first programming language. It came built-in on a lot of ‘home computers’ in the 1980s.

…and the code is also a little easier to read without all those repetitions of currentLanguage.

with() is part of the Kotlin standard library. It has an all-too-brief writeup in the official docs, and as a standard library function, you can see its code.


Don’t use Kotlin’s “for” loop when you can use its “repeat()” function

Suppose you wanted to print the string “Hello there!” three times. In any language that borrows its syntax from C, you’d probably use the classic for loop, as shown below:

// C99
for (int i = 0; i < 3; i++) {
    printf("Hello there!\n");

// JavaScript
for (let i = 0; i < 3; i++) {
    console.log("Hello there!");

With Kotlin’s for loop, you have a couple of options:

// Kotlin

// Here’s one way you can do it:
for (index in 0 until 3) {
    println("Hello there!")

// Here’s another way:
for (i in 1..3) {
    println("Hello there!")

If you’re used to programming in a C-style language, you’ll probably reach for a for loop when you need to perform a task a given number of times. The Kotlin language designers noticed this and came up with something more concise: the repeat() function:

repeat(3) {
    println("Hello there!")

As you can see, using repeat() give you a shorter, easier to read line than for. And in most cases, shorter and easier to read is better.

Do you need to know the current iteration index? Here’s how you’d get that value:

fun main() {
    repeat(3) { iteration ->
    	println("Hello there from iteration $iteration!")

Remember, you can use whatever variable name you want for that index, as long as it’s a valid name:

fun main() {
    repeat(3) { thingy ->
    	println("Hello there from iteration $thingy!")

Note that repeat() is for performing a task a known number of times, without exceptions. It’s a function that takes a closure, not a loop structure. This means that the break and continue statements won’t work:

// This WILL NOT compile!

fun main() {
    repeat(3) { iteration ->

        // 🚨🚨🚨 You can’t do this 🚨🚨🚨
        if (iteration == 1) {

        // 🚨🚨🚨 You can’t do this, either 🚨🚨🚨
        if (iteration == 2) {

        // “break” and “continue” work only
        // inside a loop, and repeat()
        // *isn’t* a loop...
        //’s a *function*!

    	println("Hello there from iteration $iteration!")

For the curious, here’s the source code for repeat():

public inline fun repeat(times: Int, action: (Int) -> Unit) {
    contract { callsInPlace(action) }

    for (index in 0 until times) {

To summarize: If you need to perform a task n times in Kotlin — and only n times — use repeat instead() of for!

Programming Reading Material

Two Kotlin/data science articles from Yours Truly!

Kotlin developers who want to get into data science: these articles are for you! They’re about using Jupyter Notebook, but with Kotlin instead of Python. Why should Pythonistas make all the big bucks?

Read the articles, which appear on (the premier mobile development site, and it’s where I learned iOS and Android dev) in this order:

  1. Create Your Own Kotlin Playground (and Get a Data Science Head Start) with Jupyter Notebook: Learn about Jupyter Notebook, get it set up on your computer, and get familiar with krangl, the Kotlin library for data wrangling.
  2. Beginning Data Science with Jupyter Notebook and Kotlin: Once you’re familiar with krangl, it’s time to get familiar with data frames and working with datasets. This article will help you get started by exploring real data, crunching it, and even getting some insights from it.


Why “?:” is called Kotlin’s “Elvis operator”

At Victoria Gonda’s presentation on Kotlin at DevFest Florida 2017, she talked about many of Kotlin’s language features. (Be sure to check out the slides from her presentation, Kotlin Uncovered!)

When she got to the “Elvis operator”?: — there were murmurs in the crowd, and I could hear people whispering “why’s it called that?”. Hopefully, the photo above answers the question: it looks like an emoticon for Elvis.

The more formal name for the Elvis operator is the null coalescing operator, and it’s a binary operator that does the following:

  • It returns the first operand if it’s non-null,
  • otherwise, it returns the second operand.

It’s far more elegant to write

val result = value1 ?: value2


if (value1 != null) {
  result = value1
} else {
  result = value2

And in case you iOS developers were wondering, Swift has a null coalescing operator: it’s ??.