【发布时间】:2015-08-01 06:18:18
【问题描述】:
假设我有这样的设置:
sealed trait Annotation {
def notes : Seq[String]
}
trait Something extends Annotation{
//do something funny
}
case class A(val i:Int)(val notes:Seq[String] = Nil) extends Something
object A{
def apply(a:A)(notes:Seq[String] = Nil):A = A(a.i)(notes)
}
case class B(val b:Boolean)(val notes:Seq[String] = Nil) extends Something
object B{
def apply(b:B)(notes:Seq[String] = Nil):B = B(b.b)(notes)
}
case class C(val s:String)(val notes:Seq[String] = Nil) extends Something
object C{
def apply(c:C)(notes:Seq[String] = Nil) :C = C(c.s)(notes)
}
尝试compile这将导致
Main.scala:10: error: in object A, multiple overloaded alternatives of method apply define
default arguments.
object A{
^
Main.scala:15: error: in object B, multiple overloaded alternatives of method apply define
default arguments.
object B{
^
Main.scala:20: error: in object C, multiple overloaded alternatives of method apply define
default arguments.
object C{
^
three errors found
我已经阅读了this,所以我至少知道为什么会发生这种情况,但是我不知道我应该如何解决这个问题。
当然,一种可能性是简单地省略默认值并在不存储任何笔记时强制客户端提供 Nil,但有更好的解决方案吗?
【问题讨论】:
-
是的,您对链接问题的看法是正确的。或者,您可以创建与应用不同的方法。例如
def withNotes(notes:Seq[String] = Nil) -
如果我们假设我应该使用 apply?
标签: scala methods compiler-errors overloading