Kotlin miniguide #13 Data classes

For classes that contain only data, Kotlin provides an implementation of

  • equals
  • getHashCode
  • toString
  • copy

Consider the following examples


class Person (name : String)

Person a = Person ("Tom")

Person b = Person ("Tom")

println(a == b)

this print false because equals compares the objects references.

If instead we use a data class:


data class Person (name : String)

Person a = Person ("Tom")

Person b = Person ("Tom")

println(a == b)

this print true because equals is called on each member, and in this case the two instances have the same name.

It is possible to copy an instance of a data class changing some of its properties:


class Person (name : String, age : Int)

Person a = Person ("Tom", 23)

Person b = a.copy(age = 35)

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...