问题描述
我在Pimp的图书馆模式上看到了一些博客,这些博客似乎在向类添加行为方面效果很好。
I've seen some blogs on the Pimp my Library pattern, and these seem to work well for adding behavior to classes.
但是如果我有一个case类,我想添加数据成员吗?作为一个case类,我不能扩展它(继承一个case类被弃用/强烈阻止)。
But what if I have a case class and I want to add data members to it? As a case class I can't extend it (inheriting from a case class is deprecated/strongly discouraged). Will any of these pimp patterns allow me to add data to a case class?
推荐答案
否 - 我没有看到你是怎么做的可以使这项工作,因为富集的实例通常被丢弃(注意:新的pimp-my-library模式称为enrich-my-library)。例如:
No - I don't see how you could make this work because the enriched instance is usually thrown away (note: newly the pimp-my-library pattern is called enrich-my-library). For example:
scala> case class X(i: Int, s: String)
defined class X
scala> implicit class Y(x: X) {
| var f: Float = 0F
| }
defined class Y
scala> X(1, "a")
res17: X = X(1,a)
scala> res17.f = 5F
res17.f: Float = 0.0
scala> res17.f
res18: Float = 0.0
您必须确保的包装实例:
You would have to make sure you kept hold of the wrapped instance:
scala> res17: Y
res19: Y = Y@4c2d27de
scala> res19.f = 4
res19.f: Float = 4.0
scala> res19.f
res20: Float = 4.0
但是,我发现这在实践中没有用。你有一个包装器;你最好做这个明确的
However, I find this not useful in practice. You have a wrapper; you're better off making this explicit
这篇关于向Scala case类添加字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!