非案例类的“复制"? [英] 'copy' for non-case classes?

查看:34
本文介绍了非案例类的“复制"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我设计不可变对象时,由于自动生成的 copy 方法,case 类非常方便.

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

但是 case 类有它们自己的问题:它们不应该被继承,而且即使您不想要它们,它们也会为您提供一个提取器.

But case classes have their own problems: they shouldn't be inherited from and they give you an extractor even if you don't want one.

所以有时我不得不使用花园式的 Scala 类.问题是我必须编写自己的不可变 API,这可能会非常重复:

So sometimes I have to use a garden-variety Scala class. The problem is that then I have to write my own immutable API, which can be pretty repetitive:

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

有没有更可扩展的方法来做到这一点?有我可以使用的编译器插件吗?

Is there a more scalable way to do this? Is there a compiler plugin I can use?

推荐答案

我不知道编译器插件,但你可以定义一个 copy 方法,就像使用 case 类生成的方法一样命名参数与默认参数相结合.

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)
}

这不像每个属性的单独方法(withNewPrincipalBalance)那样重复,并且可以禁止更改某些值(例如创建日期).

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).

这篇关于非案例类的“复制"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆