'copy' for non-case classes?

前端 未结 1 1980
悲哀的现实
悲哀的现实 2021-02-18 16:00

When I\'m designing immutable objects, case classes are incredibly handy because of the auto-generated copy method.

But case classes have their own problems

相关标签:
1条回答
  • 2021-02-18 16:54

    I don't know about a compiler plugin, but you can define a copy method just like the one generated in case classes using named arguments in combination with default arguments.

    class Debt(principalBalance: Double, name: String, endDate: LocalDate) {
      def copy(principalBalance: Double = principalBalance,
               name: String = name,
               endDate: LocalDate = endDate) = new Debt(principalBalance, name, endDate)
    }
    

    This is not as repetitive as separate methods for each property (withNewPrincipalBalance) and makes it possible to disallow changes of certain values (for example the creation date).

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