Scala:是否可以覆盖默认的案例类构造函数? [英] Scala: is it possible to override default case class constructor?

查看:40
本文介绍了Scala:是否可以覆盖默认的案例类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道这是否可能.我真正想做的是在将其中一个参数存储为 val 之前检查并可能修改它.

Just wondering if this is possible. What I would actually like to do is check and possibly modify one of the arguments before it is stored as a val.

或者,我可以使用重载并将默认构造函数设为私有.在这种情况下,我还想将伴随对象中的默认工厂构造函数设为私有,我该怎么做?

Alternatively, I could use an overload and make the default constructor private. In which case I would also like to make private the default factory constructor in the companion object, how would I do that?

非常感谢.

亚当

好吧,我发现将默认构造函数设为私有也会使默认工厂构造函数变为私有,所以我有一个解决方案,但我仍然有兴趣知道默认构造函数是否可覆盖

edit: well i figured out that making the default constructor private also makes the default factory constructor private, so i have a solution, i'm still interested to know if the default constructor is overridable though

推荐答案

次要 case 类构造函数的存在不会导致编译器在类的同伴中生成额外的工厂方法,因此您将无法获得 CaseClaseName(«secondary constructor parameter list»>) 用于创建它们.您必须使用 new 关键字.

The presence of secondary case class constructors don't cause the compiler to produce additional factory methods in the class's companion, so you won't get the convenience of CaseClaseName(«secondary constructor parameter list»>) for creating them. You'll have to use the new keyword.

最好将您描述的那种逻辑放在伴随对象的替代工厂方法中,并坚持使用主构造函数.

It's better to put the sort of logic you're describing in alternate factory methods in the companion object and stick to using the primary constructor.

这篇关于Scala:是否可以覆盖默认的案例类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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