Post

(Kotlin/Java) data class

Object / Any 상속

자바 플랫폼에서 모든 클래스는 Object(코틀린의 경우는 Any) 클래스를 상속하고, 이 최상위 클래스가 equals()/hashCode()/toString()를 가지고 있기 때문에 이를 상속하게 된다.

equals() / hashCode()

Data Classes

코틀린에서는 data 키워드를 붙여주면 equals() / hashCode() 같은 메소드를 자동으로 오버라이드해서 작성해준다!

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

  • equals()/hashCode() pair
  • toString()of the form kt "User(name=John, age=42)"
  • componentN() functions corresponding to the properties in their order of declaration
  • copy() function. 단, data 클래스는 다음 조건을 만족해야만 한다.
  • 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;

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

Note ) 주 생성자에 val, var을 모두 지정할 수 있지만 웬만하면 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.