伴侣上的Curried case类构造函数

时间:2012-10-20 13:25:22

标签: scala currying case-class companion-object

定义case类时,默认的伴随对象具有很好的curried方法来获取case类构造函数的curried版本:

scala> case class Foo(a: String, b: Int)
defined class Foo

scala> Foo.curried
res4: String => (Int => Foo) = <function1>

但是,一旦我定义了一个显式的伴随对象,这个方法就会消失:

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo(a: String, b: Int)
object Foo {}

// Exiting paste mode, now interpreting.

defined class Foo
defined module Foo

scala> Foo.curried
<console>:9: error: value curried is not a member of object Foo
              Foo.curried

我可以这样回复:

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class Foo(a: String, b: Int)
object Foo { def curried = (Foo.apply _).curried }

// Exiting paste mode, now interpreting.

defined class Foo
defined module Foo

scala> Foo.curried
res5: String => (Int => Foo) = <function1>

但是,我想知道为什么它在定义明确的伴侣时会消失(例如与apply形成对比)?

(Scala 2.9.2)

1 个答案:

答案 0 :(得分:2)

Scalac为每个case class创建默认随播广告。默认随播广告实施scala.Function n

当您定义显式伴侣时,Scalac会将显式伴侣与默认伴侣合并。

如果要调用curried,则必须让明确的随播广告实施Function2。尝试:

case class Foo(a: String, b: Int)
object Foo extends ((String, Int) => Foo) {
  def otherMethod = "foo"
}