When to use case class or regular class

前端 未结 6 1762
忘掉有多难
忘掉有多难 2020-12-24 10:43

I have some misunderstanding in what cases I should use case class or regular class following by best practices. I have already read about differences of both classes but ca

6条回答
  •  时光说笑
    2020-12-24 11:12

    Normal classes are classes as classes in Java. It can contain both state and functionality.
    Case classes are like data POJO in Java. classes that hold state, which can be used by functions (usually in other classes).

    When you are implementing data POJO in Java you should set the variable it hold, add getter and setter for them, implement hashcode and equals, and probably implement toString.
    Usually it's not that bad since after defining the variables, the IDE can generate all for you, but if you change/add variables then you should remember to update all the methods.
    in case classes you define the variables (or better values) and the compiler generate all the methods for you. So you gain both, no boilerplate and updated functionality.
    For case classes the compiler also generate more functionality, that you don't and can't have in Java, the copy function and apply/unapply in the companion object.

提交回复
热议问题