A Quick Note About Equality

In most programming languages, the == operator represents some form of an equality check. The exact meaning of == varies by language.

For example, in the case of Java, == means instance equality, where the left hand and right hand objects are the exact same object. For content equality, Java uses an equals() method. This has been known to confuse many developers over the years:

String value = "something"

System.out.println(value.toUpperCase().toLowerCase() == value);       // prints false
System.out.println(value.toUpperCase().toLowerCase().equals(value));  // prints true

In Kotlin, == is used to mean content equality, the way it is for many other programming languages. === (three equals signs) is the operator for instance equality:

  val value = "something"

  println(value.toUpperCase().toLowerCase() == value)   // prints true
  println(value.toUpperCase().toLowerCase() === value)  // prints false in Kotlin/JVM and true in Kotlin/JS

Here, val defines a variable, named value. We will explore variables in greater detail later in the book.

What you get as the result of a content equality check (==) is determined by Kotlin. What you get as the result of an instance equality check (===) is determined a bit by Kotlin but mostly by the Kotlin environment. For example, if you run the above code in the Kotlin/JS-based Klassbook, you get:

true
true

If you run that same code in an Android app or some other Kotlin/JVM project, you get:

true
false

The discrepancy has to do with the way Kotlin “transpiles” its code into JavaScript and the way that JavaScript compares strings, as is outlined in this Stack Overflow answer.

For the vast majority of your Kotlin work, you will be using content equality, not instance equality, and therefore the difference in how string instance equality is handled will not affect you.


Prev Table of Contents Next

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