Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Data Classes and Destructuring

Kotlin Data Classes and Destructuring

Data classes are designed to hold data: simply put data before class and the compiler automatically generates a set of common methods.

These methods include equals, hashCode, toString, componentN, and copy, saving you a lot of boilerplate.

Together with destructuring declarations, you can also unpack an object's properties into several variables at once.


Defining a data class

A data class is simple to write: the primary constructor must have at least one parameter, and every parameter must be marked val or var.

Example

// The data keyword goes before class

data

class

RunoobSite

(

val name

:

String

, val url

:

String

, val age

:

Int

)

fun main

(

)

{

    val site

=

RunoobSite

(

"Runoob Tutorial"

,

"www.runoob.com"

,

12

)

    println

(

site

)

     

// Auto-generated toString()

    println

(

site.

name

)

// Properties are accessed as usual

    val same

=

RunoobSite

(

"Runoob Tutorial"

,

"www.runoob.com"

,

12

)

    println

(

site

==

same

)

                             

// Auto-generated equals()

    println

(

site.

hashCode

(

)

==

same.

hashCode

(

)

)

       

// Auto-generated hashCode()

}



RunoobSite(name=Runoob Tutorial, url=www.runoob.com, age=12)

Runoob Tutorial

true

true

If you wrote the same thing with a regular class, you would have to implement all these methods yourself, which is very verbose.


Auto-generated members

The methods generated for a data class have fixed semantics; the table below can serve as a quick reference.

members Signing Purpose
equals() equals(other: Any?): Boolean Compares primary constructor properties one by one
hashCode() hashCode(): Int Kept consistent with equals to ensure correct behavior in hash tables
toString() toString(): String Produces "ClassName(property=value, property=value)"
componentN() component1(), component2(), and so on Support destructuring declarations, in the same order as the primary constructor parameters
copy() copy(...): ClassName Creates a copy of the object, allowing you to change only a few properties

Only properties declared in the primary constructor take part in equals, hashCode, toString, and componentN.

Properties declared in the class body are not included in these generated methods.


Requirements for generation

You cannot turn just any class into a data class by adding data; all of the following conditions must be met.

Conditional Description Counter-example
At least one primary constructor parameter Without parameters, no meaningful methods can be generated data class Empty()
Parameters must be marked val or var Otherwise the parameter is not a property and cannot take part in generation data class User(name: String)
Cannot be abstract An abstract class cannot be instantiated abstract data class A(val id: Int)
Cannot be open A data class is final itself open data class B(val id: Int)
Cannot be sealed Sealed classes belong to a different category sealed data class C(val id: Int)
Cannot be inner An inner class cannot be a data class inner data class D(val id: Int)

Example

// Correct: at least one primary constructor parameter, all marked val / var

data

class

RunoobA

(

val id

:

Int

)

// Wrong: the primary constructor has no parameters

// data class RunoobB()   // Data class must have at least one primary constructor parameter

// Wrong: the parameter has no val / var, it is just a regular parameter

// data class RunoobC(name: String)

// Wrong: cannot be abstract / open / sealed / inner

// abstract data class RunoobD(val id: Int)

// open data class RunoobE(val id: Int)

fun main

(

)

{

    println

(

RunoobA

(

1

)

)

}



RunoobA(id=1)

A data class can implement interfaces, but it is final and cannot be subclassed.

It can also have a class body in which you define additional functions and properties.


copy() and partial modification

Data classes are well suited to immutable data; when you need to change a field, use copy to create a new object instead of modifying the original.

Every parameter of copy has a default value taken from the corresponding property of the original object, so you only need to specify the ones you want to change.

Example

data

class

RunoobSite

(

val name

:

String

, val url

:

String

, val age

:

Int

)

fun main

(

)

{

    val site

=

RunoobSite

(

"Runoob Tutorial"

,

"www.runoob.com"

,

12

)

   

// Change only url and keep the other fields unchanged

    val mirror

=

site.

copy

(

url

=

"m.runoob.com"

)

    println

(

mirror

)

   

// Change several fields at once

    val renamed

=

site.

copy

(

name

=

"RUNOOB tutorial"

, age

=

13

)

    println

(

renamed

)

   

// No arguments = shallow-copy a new object

    val same

=

site.

copy

(

)

    println

(

same

==

site

)

   

// Same properties, structurally equal

    println

(

same

===

site

)

 

// But not the same object

}



RunoobSite(name=Runoob Tutorial, url=m.runoob.com, age=12)

RunoobSite(name=RUNOOB 教程, url=www.runoob.com, age=13)

true

false

copy performs a shallow copy; reference-type fields inside the object still point to the same instances.


Destructuring declarations

A data class automatically generates component1, component2, and so on, so you can unpack an object into multiple variables.

The order of the variables matches the order of the primary constructor parameters, not the order in which properties appear in the class body.

Example

data

class

RunoobSite

(

val name

:

String

, val url

:

String

, val age

:

Int

)

fun main

(

)

{

    val site

=

RunoobSite

(

"Runoob Tutorial"

,

"www.runoob.com"

,

12

)

   

// Destructure in primary constructor parameter order

    val

(

name, url, age

)

=

site

    println

(

"Name: $name, URL: $url, Age: $age"

)

   

// Only one field matters; use underscores as placeholders for the rest (since Kotlin 1.1)

    val

(

_, siteUrl, _

)

=

site

    println

(

"Only the URL: $siteUrl"

)

   

// Destructuring is also used when iterating over a Map

    val scores

=

mapOf

(

"runoob"

to

95

,

"RUNOOB"

to

88

)

   

for

(

(

key, value

)

in scores

)

{

        println

(

"$key -> $value"

)

   

}

}



名称:Runoob Tutorial,网址:www.runoob.com,年龄:12

只要网址:www.runoob.com

runoob -> 95

RUNOOB -> 88

A regular class can also support destructuring as long as it declares componentN operator functions itself.

Example

class

RunoobPoint

(

val x

:

Int, val y

:

Int

)

{

   

// Declare componentN manually so a regular class supports destructuring

    operator fun component1

(

)

=

x

    operator fun component2

(

)

=

y

}

fun main

(

)

{

    val

(

x, y

)

=

RunoobPoint

(

3

,

4

)

    println

(

"x=$x, y=$y"

)

}



x=3, y=4

Note:Underscore placeholders in destructuring have been supported since Kotlin 1.1. In older versions, to skip a position you had to give it an unused name.


Equality of data classes

A data class's equals only compares primary constructor properties; properties in the class body are excluded.

This means two objects may be equal even though their class-body properties differ.

Example

data

class

RunoobUser

(

val name

:

String

)

{

    var city

:

String

=

"Beijing"

 

// Class-body property, not included in equals / hashCode

}

fun main

(

)

{

    val a

=

RunoobUser

(

"runoob"

)

    val b

=

RunoobUser

(

"runoob"

)

    a.

city

=

"Shanghai"

    b.

city

=

"Guangzhou"

    println

(

a

==

b

)

           

// Only name is compared, so this is true

    println

(

a.

city

==

b.

city

)

 

// Class-body properties compared separately, false

}



true

false

This is a reminder that any field that should take part in equality checks belongs in the primary constructor.


Pair and Triple

The standard library provides two ready-made data classes for temporarily grouping two or three values.

Pair holds two values and Triple holds three; both support destructuring and copy.

Example

fun main

(

)

{

   

// to is an infix function equivalent to Pair("runoob", 95)

    val score

:

Pair

<

String

, Int

=

"runoob"

to

95

    println

(

score.

first

)

   

// First value

    println

(

score.

second

)

 

// Second value

   

// Destructure the Pair

    val

(

name, value

)

=

score

    println

(

"$name's score is $value"

)

   

// Triple holds three values

    val info

=

Triple

(

"RUNOOB"

,

"www.runoob.com"

,

2026

)

    val

(

site, url, year

)

=

info

    println

(

"$site - $url - $year"

)

   

// Pair is also a data class and has copy as well

    println

(

score.

copy

(

second

=

100

)

)

}



runoob

95

runoob 的分数是 95

RUNOOB - www.runoob.com - 2026

(runoob, 100)

Pair and Triple are convenient for returning several values temporarily from a function; when the meaning of the fields is unclear, prefer a custom data class.


data object (since Kotlin 1.9)

A plain object prints an object address, while a data object automatically generates a meaningful toString.

Since Kotlin 1.9 you can declare a singleton with data object, which also generates equals and hashCode.

Example

// Since Kotlin 1.9: data object auto-generates toString / equals / hashCode

data object RunoobConfig

{

    val siteName

:

String

=

"RUNOOB"

}

fun main

(

)

{

    println

(

RunoobConfig

)

                   

// Prints the object name instead of an address

    println

(

RunoobConfig

==

RunoobConfig

)

   

// A singleton is always equal to itself

    println

(

RunoobConfig.

siteName

)

}



RunoobConfig

true

RUNOOB

The most common use of a data object is representing a branch with no data in a sealed class hierarchy.

Example

sealed

interface

RunoobState

{

    data object Loading

:

RunoobState                        

// Singleton branch with no data

    data object Empty

:

RunoobState                          

// Singleton branch with no data

    data

class

Success

(

val data

:

String

)

:

RunoobState      

// Branch with data

}

fun describe

(

state

:

RunoobState

)

:

String

=

when

(

state

)

{

    RunoobState.

Loading

->

"Loading"

    RunoobState.

Empty

->

"No data yet"

    is RunoobState.

Success

->

"Success: ${state.data}"

}

fun main

(

)

{

    println

(

describe

(

RunoobState.

Loading

)

)

    println

(

describe

(

RunoobState.

Empty

)

)

    println

(

describe

(

RunoobState.

Success

(

"www.runoob.com"

)

)

)

}



加载中

暂无数据

成功:www.runoob.com


Common questions

Below are a few common problems encountered when using data classes.

Why doesn't changing a property take effect

Data class properties are usually declared as val and are immutable; the correct approach is to create a new object with copy.

If you really need a mutable property, declare it as var, but keep in mind that it still participates in equals and hashCode.

Why aren't class-body properties included in comparisons

This is a compiler convention: only primary constructor parameters are generated into equals, hashCode, and toString.

Put the fields you need to compare in the primary constructor, not in the class body.

What if two objects share an internal object after copy

copy only copies references, not the objects they point to, so it is a shallow copy.

If there is a mutable collection inside, you need to make a deep copy manually.

How to choose between Pair and a custom data class

When you only need to return two or three values temporarily inside a function, Pair or Triple is simpler.

As soon as those values cross module boundaries or need descriptive field names, switch to a custom data class.