In this tutorial you will learn about Operators via simple step by step examples.

Let us look at a simple Operators examples written in Kotlin Programming Language. Follow the following steps:

Step 1: Create Project

  1. Open your favorite Kotlin IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Add Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Our code will comprise the following Kotlin files:

  • ComparableRange.kt
  • CompareTo.kt
  • DestructuringData.kt
  • DestructuringDuo.kt
  • DestructuringMap.kt
  • NewAngle.kt
  • OperatorPlus.kt
  • ReadOnlyAndPlus.kt
  • Unexpected.kt
  • UsingOperatorsSoln1.kt
  • UsingOperatorsSoln2.kt
  • UsingOperatorsSoln3.kt

Example 1: Comparable Range

  1. In your editor or IDE, create a file known as ComparableRange.kt.
  2. Then add the following code:

(a). ComparableRange.kt

// UsingOperators/ComparableRange.kt

package usingoperators
import atomictest.eq

class F(val i: Int): Comparable<F> {
  override fun compareTo(other: F) =
    i.compareTo(other.i)
}

fun main() {
  val range = F(1)..F(7)
  (F(3) in range) eq true
  (F(9) in range) eq false
}

Example 2: Comparisons using CompareTo

  1. Next create another file known as CompareTo.kt.
  2. And add the following code:

(b). CompareTo.kt

// UsingOperators/CompareTo.kt

package usingoperators
import atomictest.eq

data class Contact(
  val name: String,
  val mobile: String
): Comparable<Contact> {
  override fun compareTo(
    other: Contact
  ): Int = name.compareTo(other.name)
}

fun main() {
  val alice = Contact("Alice", "0123456789")
  val bob = Contact("Bob", "9876543210")
  val carl = Contact("Carl", "5678901234")
  (alice < bob) eq true
  (alice <= bob) eq true
  (alice > bob) eq false
  (alice >= bob) eq false
  val contacts = listOf(bob, carl, alice)
  contacts.sorted() eq
    listOf(alice, bob, carl)
  contacts.sortedDescending() eq
    listOf(carl, bob, alice)
}

Example 3: Destructuring Data

  1. Create another file known as DestructuringData.kt.
  2. And add the following code:

(c). DestructuringData.kt

// UsingOperators/DestructuringData.kt

package usingoperators
import atomictest.eq

data class Person(
  val name: String,
  val age: Int
) {
  // Compiler generates:
  // fun component1() = name
  // fun component2() = age
}

fun main() {
  val person = Person("Alice", 29)
  val (name, age) = person
  // The Destructuring assignment becomes:
  val name_ = person.component1()
  val age_ = person.component2()
  name eq "Alice"
  age eq 29
  name_ eq "Alice"
  age_ eq 29
}

Example 4: Destructuring Duo

  1. Create another file known as DestructuringDuo.kt.
  2. And add the following code:

(d). DestructuringDuo.kt

// UsingOperators/DestructuringDuo.kt

package usingoperators
import atomictest.*

class Duo(val x: Int, val y: Int) {
  operator fun component1(): Int {
    trace("component1()")
    return x
  }
  operator fun component2(): Int {
    trace("component2()")
    return y
  }
}

fun main() {
  val (a, b) = Duo(1, 2)
  a eq 1
  b eq 2
  trace eq "component1() component2()"
}

Example 5: Destructuring Map

  1. Next create another file known as DestructuringMap.kt.
  2. And add the following code:

(e). DestructuringMap.kt

// UsingOperators/DestructuringMap.kt

import atomictest.eq

fun main() {
  val map = mapOf("a" to 1)
  for ((key, value) in map) {
    key eq "a"
    value eq 1
  }
  // The Destructuring assignment becomes:
  for (entry in map) {
    val key = entry.component1()
    val value = entry.component2()
    key eq "a"
    value eq 1
  }
}

Example 6: New Angle

  1. Next create another file known as NewAngle.kt.
  2. And add the following code:

(f). NewAngle.kt

// UsingOperators/NewAngle.kt

import atomictest.eq

fun main() {
  val list = MutableList(10) { 'a' + it }
  list[7] eq 'h' // operator get()
  list.get(8) eq 'i' // Explicit call
  list[9] = 'x' // operator set()
  list.set(9, 'x') // Explicit call
  list[9] eq 'x'
  ('d' in list) eq true // operator contains()
  list.contains('e') eq true // Explicit call
}

Example 7: Operator Plus

  1. Create a file known as OperatorPlus.kt.
  2. And add the following code:

(g). OperatorPlus.kt

// UsingOperators/OperatorPlus.kt

import atomictest.eq

fun main() {
  val mutableList = mutableListOf(1, 2, 3)
  mutableList += 4  // operator plusAssign()
  mutableList.plusAssign(5) // Explicit
  mutableList eq "[1, 2, 3, 4, 5]"
  mutableList + 99 eq "[1, 2, 3, 4, 5, 99]"
  mutableList eq "[1, 2, 3, 4, 5]"
  val list = listOf(1)  // Read-only
  val newList = list + 2  // operator plus()
  list eq "[1]"
  newList eq "[1, 2]"
  val another = list.plus(3)  // Explicit
  another eq "[1, 3]"
}

Example 8: ReadOnly and Plus

  1. Create a file known as ReadOnlyAndPlus.kt.
  2. And add the following code:

(h). ReadOnlyAndPlus.kt

// UsingOperators/ReadOnlyAndPlus.kt

import atomictest.eq

fun main() {
  var list = listOf(1, 2)
  val initial = list
  list += 3
  list eq "[1, 2, 3]"
  list = list.plus(4)
  list eq "[1, 2, 3, 4]"
  initial eq "[1, 2]"
}

Example 9: Unexpected

  1. Next create another file known as Unexpected.kt.
  2. And add the following code:

(i). Unexpected.kt

// UsingOperators/Unexpected.kt

import atomictest.eq

fun main() {
  var list = listOf(1, 2)
  list += 3  // Probably unexpected
  list eq "[1, 2, 3]"
}
  1. Next create another file known as UsingOperatorsSoln1.kt.
  2. And add the following code:

(j). UsingOperatorsSoln1.kt

// UsingOperators/UsingOperatorsSoln1.kt

package usingOperatorsExercise1
import atomictest.trace

data class DataMany(
  val a: Int = 1,
  val b: Int = 2,
  val c: Int = 3,
  val d: Int = 4,
  val e: Int = 5,
  val f: Int = 6,
  val g: Int = 7,
  val h: Int = 8,
  val i: Int = 9,
  val j: Int = 10,
)

fun all() {
  val dm = DataMany()
  val (a, b, c, d, e, f, g, h, i, j) = dm
  trace("$a $b $c $d $e $f $g $h $i $j")
  trace(dm.component1())
  trace(dm.component10())
}

fun firstHalf() {
  val dm = DataMany()
  val (a, b, c, d, e) = dm
  trace("$a $b $c $d $e")
}

fun secondHalf() {
  val dm = DataMany()
  val (_, _, _, _, _, f, g, h, i, j) = dm
  trace("$f $g $h $i $j")
}

fun interspersed() {
  val dm = DataMany()
  val (a, _, c, _, e, _, g, _, i, _) = dm
  trace("$a $c $e $g $i")
}

fun main() {
  all()
  firstHalf()
  secondHalf()
  interspersed()
  trace eq """
    1 2 3 4 5 6 7 8 9 10
    1
    10
    1 2 3 4 5
    6 7 8 9 10
    1 3 5 7 9
  """
}
  1. Next create another file known as UsingOperatorsSoln2.kt.
  2. And add the following code:

(k). UsingOperatorsSoln2.kt

// UsingOperators/UsingOperatorsSoln2.kt

package usingOperatorsExercise2
import atomictest.trace

fun create(): MutableList<Int> = MutableList(10) { it }

fun assignAppendIncrementContains() {
  trace("assignAppendIncrementContains()")
  val list = create()
  list[9] = 99
  list += 100
  list[10]++
  trace(list)
  trace(101 in list)
}

fun minus() {
  trace("minus()")
  val list = create()
  trace(list - 5)
  trace(list - 5 - 6 - 7 - 8)
  trace(list - 10)
  list -= 0
  list -= 1
  list -= -1
  trace(list)
}

fun plus() {
  trace("plus()")
  var list = create() + 11 + 12 + 13
  list += 14
  trace(list)
}

fun main() {
  assignAppendIncrementContains()
  minus()
  plus()
  trace eq """
    assignAppendIncrementContains()
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 99, 101]
    true
    minus()
    [0, 1, 2, 3, 4, 6, 7, 8, 9]
    [0, 1, 2, 3, 4, 9]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    [2, 3, 4, 5, 6, 7, 8, 9]
    plus()
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]
  """
}
  1. Next create another file known as UsingOperatorsSoln3.kt.
  2. And add the following code:

(l). UsingOperatorsSoln3.kt

// UsingOperators/UsingOperatorsSoln3.kt

package usingOperatorsExercise3
import atomictest.trace
import kotlin.random.Random

data class N(var n: Int) : Comparable<N> {
  override fun compareTo(other: N) =
    n.compareTo(other.n)
  override fun toString() = "N($n)"
}

fun main() {
  val rnd = Random(47) // For repeatability
  val key = N(11)
  val map = mutableMapOf(key to 47)
  trace(map[key])
  key.n++
  trace(map[key])
  val list = List(5) { N(it) }.shuffled(rnd)
  trace("list: $list")
  val set = list.toSortedSet()
  trace("sorted set (1): $set")
  set.minOrNull()!!.n += 2
  trace("sorted set (2): $set")
  trace eq """
    47
    null
    list: [N(4), N(0), N(2), N(3), N(1)]
    sorted set (1): [N(0), N(1), N(2), N(3), N(4)]
    sorted set (2): [N(2), N(1), N(2), N(3), N(4)]
  """
}

Step 4: Run

Copy the code, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code License