So. Many. Operators.

There are many operators in Kotlin, including some things that you might not expect to be considered operators.

in

in is an operator. It maps to the contains() function. So, any type that supports contains()String, List, etc. — can be used with in:

fun main() {
  println("foo" in "foobar")
}

While in happens to be an operator, we can create other “operators” that syntactically look like in. For example, we used to in mapOf():

  val things = mapOf("key" to "value", "other-key" to "other-value")

  println(things::class)
  println(things)
  println(things.size)

to is not an operator. Instead, it is an infix function, and we can create our own infix functions.

Indexed Access

Square-bracket syntax gets mapped to operators. [] maps to get(), while []= maps to set().

In the case of get(), the comma-delimited list of arguments in the brackets gets passed to the get() function. As a result, we can use [] for both a single index — like we do with List or Map — and for multiple indexes.

In the case of set(), the comma-delimited list of arguments in the brackets gets passed to the set() function, followed by the value to the right of the operator. So, something['foo'] = 3 is equivalent to something.set('foo', 3).

Invocation

When we see syntax like foo(), we assume that foo is the name of a function. Most of the time, that is the case. However, it could also be an object whose type has an invoke() function:

operator fun String.invoke(count: Int) = this.chunked((this.length / count) + 1)

fun main() {
  println("This is a reasonably long string"(3))
}

Here we have the same function that we had for div(), except now it is named invoke(). We call it by “calling a function” on the object, passing an Int parameter.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.