Post

(Kotlin/Java) data class

Data Class

1
2
3
4
data class User(
  val name: String, 
  val age: Int
)
  • 코틀린에서는 data 키워드를 붙여주면 equals() / hashCode() 같은 메소드를 자동으로 오버라이드해준다!
    • equals()/hashCode() pair
      • 코틀린에서 x.equals(y)x == y와 같다. (내부적으로 equals를 호출한다.)
      • 참조 비교를 위해서는 x === y 를 사용한다.
    • toString()of the form kt "User(name=John, age=42)"
    • componentN() functions corresponding to the properties in their order of declaration
    • copy() function.
  • 단, data class 클래스는 아래 조건을 만족해야만 한다.
    • The primary constructor needs to have at least one parameter;
    • All primary constructor parameters need to be marked as val, var;
    • Data classes cannot be abstract, open, sealed, inner;

toString()/equals()/hashCode()는 결과를 산출할 때 주 생성자에 나열된 프로퍼티만 사용하기 때문에, 주 생성자 밖에 정의된 프로퍼티는 고려하지 않는다.

주 생성자에 val, var을 모두 지정할 수 있지만, data class의 의미를 생각해보면 불변 클래스로 사용하는 것이 더 좋아보인다.
⇒ 모든 필드 val로 지정하고, 변경이 필요한 프로퍼티가 생기면 copy() 사용.

왜 data class를 상속해서 쓸 수 없을까?

stackoverflow.com/questions/26444145/extend-data-class-in-kotlin

The truth is: data classes do not play too well with inheritance. We are considering prohibiting or severely restricting inheritance of data classes. For example, it’s known that there’s no way to implement equals() correctly in a hierarchy on non-abstract classes.
So, all I can offer: don’t use inheritance with data classes.

abstract class 상속이나 interface 구현은 가능하다.

data class와 HashMap (객체 정의 vs 맵에 key-value로 저장)

HashMap이 더 유연하지만, 유연하다는 것은 곧 비싸다는 것을 의미하므로…
data class에 비해 메모리를 많이 사용하며 느리고, primitive type의 boxing을 강제한다는 단점이 있다.

가독성도 당연히 필드를 바로 확인할 수 있는 data class가 좋은 편이나, HashMap도 주석으로 제공할 수 있으니 이건 크게 문제가 되지는 않는다.

아무튼, 대체로 data class를 사용하는게 도움이 되며 유연성이 필요한 경우 HashMap을 고려하면 되겠다.

This post is licensed under CC BY 4.0 by the author.