본문

171102(목) - Kotlin docs (Data Classes)

Kotlin docs


Data Classes

- frequently create classes purpose to hold data.

- 이런 class에서 some standard functionality and utility functions는 often data에서 mechanically derivable 된다.

- Kotlin에서는 이를 data class라고 부른다.

data class User(val name: String, val age: Int)

- compiler는 primary constructor에서 선언된 모든 properties에서 아래 members를 자동으로 derives한다.

· equals() / hashCode() pair

· toString() (from "User(name=John, age=42)")

· componentN() functions는 declaration order대로 properties에 대응된다.

· copy()


- generated code의 consistency and meaningful behavior를 ensure하려면, data classes는 아래 사항을 fulfill 해야 한다.

· primary constructor needs to have at least of one parameter

· all primary constructor parameters need to be marked as val or var

· data classes는 cannot abstract, open, sealed or inner

· (before 1.1) data classes는 only implement interfaces


- member generation은 member inheritance와 관련하여 아래의 rules를 따른다.

· data class body or final implementations in a superclass에서 equals(), hashCode() or toString()을 explicit하게 implementations한 경우, 이러한 functions가 생성되지 않고 existing implementations가 사용된다.


· supertype에 open and return compatible types인 componentN() functions가 있는경우, 해당 함수가 data class에 대해 generated되고 supertype override


· incompatible signatures or being final로 인하여 functions cannot be overridden 인 경우 error is reported

· componentN() and copy() functions의 explicit implementations는 not allowed


- since 1.1, data classes extend other classes

- JVM에서 생성된 class에 parameterless constructor가 필요한 경우 all properties have to be specified.

data class User(val name: String = "", val age: Int = 0)

Copying

- often case, some of properties를 altering하여 copy an object, but keeping the rest unchanged.

fun copy(name: String = this.name, age: Int = this.age) = User(name, age)     
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)

Data Classes and Destructuring Declarations

- data classes용으로 생성된 component functions는 destructuring declarations로 사용가능

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

Standard Data Classes

- standard library provides Pair and Triple

- most cases named data classes는 properties에 meaningful names를 제공하여 code를 more readable하기 때문에 better design choice

'Mobile > Kotlin' 카테고리의 다른 글

171212(화) - any  (0) 2017.12.12
171211(월) - Using scope functions  (0) 2017.12.11
170828(월) - Kotlin docs (Extensions)  (0) 2017.08.28
170823(수) - Kotlin docs (Visibility Modifiers)  (0) 2017.08.23
170821(월) - Kotlin docs (Interfaces)  (0) 2017.08.21

공유

댓글