2010-03-08 69 views

回答

151

重載構造函數是不是特別的情況下類:

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

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

但是,您可能喜歡也超載在同伴的對象,當你忽略new這就是所謂的apply方法。

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

Foo(1, 2) 
Foo(1) 

在Scala 2.8中,通常可以使用命名參數和默認參數來代替重載。

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

很不錯的:)我一直在尋找的東西像斯卡拉後備值,它與2.8新?我不知道:) – Felix 2010-03-10 14:23:39

+0

是的,命名參數和默認參數在Scala 2.8中是新的。 – retronym 2010-03-10 22:17:00

+7

Martin Odersky解釋了爲什麼不會自動添加其他應用方法:http://www.scala-lang.org/node/976 – 2010-04-15 12:56:43

17

您可以按照常規方式定義重載構造函數,但要調用它,必須使用「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) 
+2

這並不完全正確 - 你可以在同伴對象聲明爲正常 – 2010-03-08 12:57:20