Scala 案例类的重载构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2400794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:59:43  来源:igfitidea点击:

Overload constructor for Scala's Case Classes?

scalaconstructoroverloadingscala-2.8case-class

提问by Felix

In Scala 2.8 is there a way to overload constructors of a case class?

在 Scala 2.8 中有没有办法重载 case 类的构造函数?

If yes, please put a snippet to explain, if not, please explain why?

如果是,请放一个片段来解释,如果不是,请解释为什么?

回答by retronym

Overloading constructors isn't special for case classes:

重载构造函数对于 case 类并不特殊:

case class Foo(bar: Int, baz: Int) {
  def this(bar: Int) = this(bar, 0)
}

new Foo(1, 2)
new Foo(1)

However, you may like to also overload the applymethod in the companion object, which is called when you omit new.

但是,您可能还想重载apply伴随对象中的方法,当您省略new.

object Foo {
  def apply(bar: Int) = new Foo(bar)
}

Foo(1, 2)
Foo(1)

In Scala 2.8, named and default parameters can often be used instead of overloading.

在 Scala 2.8 中,通常可以使用命名参数和默认参数来代替重载。

case class Baz(bar: Int, baz: Int = 0)
new Baz(1)
Baz(1)

回答by Lukas Rytz

You can define an overloaded constructor the usual way, but to invoke it you have to use the "new" keyword.

您可以按照通常的方式定义重载构造函数,但要调用它,您必须使用“new”关键字。

scala> case class A(i: Int) { def this(s: String) = this(s.toInt) }
defined class A

scala> A(1)
res0: A = A(1)

scala> A("2")
<console>:8: error: type mismatch;
 found   : java.lang.String("2")
 required: Int
       A("2")
         ^

scala> new A("2")
res2: A = A(2)