Scala 案例类的重载构造函数? [英] Overload constructor for Scala's Case Classes?

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

问题描述

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

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

如果是,请放一个片段来解释,如果不是,请解释原因?

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

推荐答案

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

Overloading constructors isn't special for case classes:

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

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

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

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

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

Foo(1, 2)
Foo(1)

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

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

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

这篇关于Scala 案例类的重载构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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