From Java to Kotlin - Operators & Operators Overloading


1..10 enumerates all numbers from 1 to 10
a..b is the same as a.rangeTo(b)

Referential vs Structural Equality

Referential equality. Two separate references point to the exact same instance in memory
=== / !== check if it’s same instance

Structural equality. Two objects are separate instances in memory but have the same value
== / != check if they have the same values


To check whether an element is in a collection or range and also to iterate over a collection.

val ints = arrayOf(1,2,3,4)
val a = 3 in ints // same as ints.contains(3)
val b = 5 !in ints // same as !ints.contains(5)

Index operator

// get
a[i] // means `a.get(i)`   
a[i, j] // means `a.get(i, j)`  

// set
a[i] = b // means `a.set(i,b)`  
a[i, j] = b // means `a.set(i,j,b)`

Operator Overloading

It’s the ability to define functions or classes that use operators (for example, +, += or > but not ===).

Kotlin has a limited set of operators that you can overload, and each one corresponds to the name of the function you need to define in your class.
Operators can only be defined as member functions or extension functions.

If you want to be able to write 1.5 * p in addition to p * 1.5 you need to define 2 separate operators. The return type of an operator function can also be different from either of the operand types.

// A function called plus is defined.
//    It implements addition in the class
class MyClass(val a: Int, val b: Int) {
  operator fun plus(myClass: MyClass): MyClass {
    return MyClass(a + myClass.a, b + myClass.b)

// usage
val m1 = MyClass(1, 2)
val m2 = MyClass(3, 4)
val m3 = m1 + m2