案例类是否允许使用构造函数?
我有一个案例类(让我们将其命名为 Stuff
),我希望能够通过扩展特征(将其称为 Marker
)在运行时创建匿名子类。下面是 REPL 会话的片段,它说明了我正在尝试执行的操作:
scala> trait Marker
defined trait Marker
scala> case class Stuff(i: Int)
defined class Stuff
scala> val a = Stuff(1)
a: Stuff = Stuff(1)
scala> val b = new Stuff(1) with Marker
b: Stuff with Marker = Stuff(1)
请注意如何使用 Stuff.apply()
实例化 a
,而在 b< /code> 的 case 我正在调用 case 类的构造函数。
我的问题是:使用构造函数实例化案例类是否合理?在我看来确实如此,因为案例类通常提供便利,例如 ==
、< code>.equals() 和 .hashCode()
都可以。我是否遗漏了任何可能使我正在做的事情成为坏事(TM)的事情?
scala> a == b
res0: Boolean = true
scala> a.equals(b)
res1: Boolean = true
scala> a.hashCode == b.hashCode
res2: Boolean = true
I have a case class (let's name it Stuff
) that I want to be able to create anonymous subclasses of at run time by extending a trait (call it Marker
). Here's a snippet of a REPL session that illustrates what I'm trying to do:
scala> trait Marker
defined trait Marker
scala> case class Stuff(i: Int)
defined class Stuff
scala> val a = Stuff(1)
a: Stuff = Stuff(1)
scala> val b = new Stuff(1) with Marker
b: Stuff with Marker = Stuff(1)
Note how a
is instantiated using Stuff.apply()
, while in b
's case I'm calling the case class' constructor.
My question is: is instantiating case classes using a constructor kosher? It appears to me that it is, since the usual conveniences provided by case classes, such as ==
, .equals()
, and .hashCode()
, all work. Am I missing anything that would brand what I'm doing a Bad Thing (TM)?
scala> a == b
res0: Boolean = true
scala> a.equals(b)
res1: Boolean = true
scala> a.hashCode == b.hashCode
res2: Boolean = true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是
Stuff.apply
的实现方式:因此,使用
new Stuff
没有任何坏处。Here's how
Stuff.apply
is implemented:So there's no harm at all in using
new Stuff
.对于问题
答案肯定是肯定的。类似的事情
根本不会造成任何问题。现在,
new Stuff(1) with Marker
有所不同,因为创建了Stuff
的匿名子类。不过,我相信这仍然没有问题。当案例类从其他案例类继承时,我所知道的问题就会出现,而您却没有这样做。但我可能不知道一些事情。编辑:刚刚在 REPL 中测试了匹配:
To the question
the answer is definitely yes. Something like
poses no problems at all. Now,
new Stuff(1) with Marker
is different because an anonymous subclass ofStuff
is created. I believe, though, that it's still unproblematic. The problems I know about appear when case classes inherit from other case classes, and you aren't doing that. But I may be unaware of something.EDIT: just tested matching in the REPL: