非案例类的“复制"?

编程入门 行业动态 更新时间:2024-10-28 06:21:55
本文介绍了非案例类的“复制"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我设计不可变对象时,由于自动生成的 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).

更多推荐

非案例类的“复制"?

本文发布于:2023-11-25 07:39:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:案例   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!