Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Object Creation and Equality | Kotlin Idioms and Control Flow
Kotlin for Java Developers

bookObject Creation and Equality

Scorri per mostrare il menu

When creating objects in Kotlin, you use a concise and straightforward syntax. Unlike Java, you do not need the new keyword. You simply call the class constructor directly. For example, if you have a class named Person, you can create an instance by writing val person = Person("Alice"). This approach makes object creation more readable and less verbose compared to Java.

Kotlin also introduces two distinct equality operators: == and ===. The == operator checks for structural equality, meaning it compares the contents of the objects by calling the equals() method under the hood. On the other hand, the === operator checks for referential equality—it returns true if both references point to the exact same object in memory.

Understanding the difference between these operators is crucial when transitioning from Java. In Java, == checks for reference equality, and .equals() checks for structural equality. Kotlin's == is more like Java's .equals(), while Kotlin's === is equivalent to Java's == for object references.

Main.kt

Main.kt

copy
12345678910111213
package com.example data class Person(val name: String) fun main() { val personA = Person("Alice") val personB = Person("Alice") val personC = personA println(personA == personB) // true: structural equality println(personA === personB) // false: referential equality println(personA === personC) // true: same reference }

In the code above, you see how Kotlin distinguishes between structural and referential equality. The line personA == personB evaluates to true because both objects have the same property values and the data class automatically implements equals(). However, personA === personB is false, because they are two different instances in memory, even though their contents are the same. personA === personC is true, since personC is just another reference to the exact same object as personA.

When deciding which equality operator to use, consider whether you care about the contents of the objects or their identity in memory. Use == if you want to check if two objects are equal in value, similar to using equals() in Java. Use === if you need to know whether two references point to the same object, just like the == operator in Java when used with objects.

question mark

What does the === operator check in Kotlin?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 1
some-alt