Scala: is it possible to override default case class constructor?

蓝咒 提交于 2019-11-28 09:44:56

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.

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.

wheaties

You can overload constructors. It's the same as in C++ or Java. Simply make another constructor.

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

Or you can see this SO post.

You can turn a regular class into a pseudo-case-class by writing your own apply (for the factory) and unapply (for the pattern match) methods in the companion object. Or, you could simply write a named factory method in the case class's companion object.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!