Hanbit the Developer

Kotlin Documentation | Data classes 본문

Kotlin

Kotlin Documentation | Data classes

hanbikan 2023. 5. 23. 12:17

Kotlin Documentation 시리즈에 대해

Category: Concepts - Classes and objects

문서 링크: https://kotlinlang.org/docs/data-classes.html


컴파일러가 자동으로 다음 메소드들을 추가한다:

  • equals()
  • hashCode()
  • toString() → “User(name=John, age=42)”
  • componentN()
  • copy()

cannot be abstract, open, sealed, or inner

Properties declared in the class body

data class Person(val name: String) {
    var age: Int = 0
}

val person1 = Person("John")
val person2 = Person("John")
person1.age = 10
person2.age = 20

다만 name에 대한 component1() 함수만 생성됨

Data classes and destructing declarations

val jane = User("Jane", 35)
val (name, age) = jane
println("$name, $age years of age") // prints "Jane, 35 years of age"