20

只是想知道这是否可能。我实际上想要做的是检查并可能修改其中一个参数,然后再将其存储为 val。

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

非常感谢。

亚当

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

4

4 回答 4

25

You do not have the option of changing the way the default constructor stores its parameters (e.g. by modifying the parameters before they are stored as vals) but you do have the option of throwing an exception if the parameters are wrong (this will occur after the parameters are stored)

case class Foo(x:Int){
    if (x<0) throw SomeException;
}

You also have the option of implementing additional constructors that call the first constructor

case class Foo(x:Int){
     def this(x:Int,y:Int) = this(x+y)
}

but those don't get factory methods.

You could easily create the factory method yourself by adding it to the companion object

object Foo{
     def apply(x:Int,y:Int) = new Foo(x,y)
}

Anything else more complicated than that, and you have to forgo the case class and implement it's parts on your own: apply, unapply, equals, and hashCode. Programming in Scala talks about how to do all of these, giving good formulas for equals and hashCode.

于 2010-09-08T01:25:21.930 回答
11

辅助案例类构造函数的存在不会导致编译器在类的同伴中生成额外的工厂方法,因此您不会获得CaseClaseName(«secondary constructor parameter list»>)创建它们的便利。您必须使用new关键字。

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

于 2010-09-03T15:16:04.390 回答
3

您可以重载构造函数。它与 C++ 或 Java 中的相同。只需制作另一个构造函数。

class Foo( _input:Int ){
    def this() = this( 0 )
}

或者你可以看到这个SO 帖子。

于 2010-04-18T03:40:52.923 回答
1

您可以通过在伴生对象中编写自己的apply(用于工厂)和unapply(用于模式匹配)方法将常规类转换为伪案例类。或者,您可以简单地在案例类的伴随对象中编写一个命名工厂方法。

于 2010-09-05T02:22:29.727 回答