12

在定义案例类时,默认的伴随对象有很好的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)?

(斯卡拉 2.9.2)

4

1 回答 1

2

Scalac 为每个case class. 默认伴侣实现scala.Functionn

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

如果你想调用curried,你必须让你的显式同伴实现Function2。尝试:

case class Foo(a: String, b: Int)
object Foo extends ((String, Int) => Foo) {
  def otherMethod = "foo"
}
于 2012-11-23T18:52:26.530 回答