case class private constructor - need for readResolve implementation

后端 未结 1 1244
旧时难觅i
旧时难觅i 2021-01-16 23:36

I was just googling to find out how to create a case class with private constructor. Below is the correct way for doing this as described in

How to override apply i

1条回答
  •  旧巷少年郎
    2021-01-16 23:56

    The readResolve implementation is there to prevent the creation of invalid instances of the case class by editing serialised copies of the class.

    Depending on how much you trust the environment in which the code will be used, you may feel you can safely ignore this risk.

    It comes about because case classes extend Serializable, and so may end up getting serialised and written out to file (or DB, or wherever). At this point the serialised copy in the file/DB/wherever could be edited to create an invalid value (eg. making s lower case). On deserialising back, the 'live' instance will then be invalid, unless the readResolve method that is used in the deserialisation process is overriden to prevent this.

    0 讨论(0)
提交回复
热议问题