gpt4 book ai didi

Scala - 处理 "multiple overloaded alternatives of method ... define default arguments"

转载 作者:行者123 更新时间:2023-12-02 10:40:38 25 4
gpt4 key购买 nike

假设我有这样的设置:

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,但有更好的解决方案吗?

最佳答案

我的第一个猜测是简单地明确默认参数:

case class A(i: Int)(val notes: Seq[String]) extends Something
object A {
def apply(i: Int): A = new A(i)(Nil)
def apply(a: A)(notes: Seq[String]): A = new A(a.i)(notes)
def apply(a: A): A = new A(a.i)(Nil)
}

然而,现在,因为柯里化(Currying),你只有一个函数 Int => AInt => Seq[String] => A (与 A => A 类似)在范围内具有相同的名称。

如果您避免使用currying,则可以手动定义重载方法:
case class B(b: Boolean, notes: Seq[String]) extends Something

object B {
def apply(b: Boolean): B = B(b, Nil)
def apply(b: B, notes: Seq[String] = Nil): B = B(b.b, notes)
}

但是,自从 notes现在是与 b 相同的参数列表的一部分, 案例类方法的行为如 toString被改变。
println(B(true))                  // B(true,List())
println(B(true, List("hello"))) // B(true,List(hello))
println(B(B(false))) // B(false,List())

最后,为了更接近地模仿原始行为,您可以实现自己的 equals , hashCode , toString , 和 unapply方法:
class C(val s:String, val notes:Seq[String] = Nil) extends Something {

override def toString = s"C($s)"

override def equals(o: Any) = o match {
case C(`s`) => true
case _ => false
}

override def hashCode = s.hashCode
}

object C{
def apply(s: String, notes: Seq[String]) = new C(s, notes)
def apply(s: String): C = C(s, Nil)
def apply(c:C, notes:Seq[String] = Nil): C = C(c.s, notes)
def unapply(c: C): Option[String] = Some(c.s)
}

例子:
val c1 = C("hello")
val c2 = C("hello", List("world"))
println(c1) // C(hello)
println(c2) // C(hello)
println(c1 == c2) // true
c1 match { // hello
case C(n) => println(n)
case _ =>
}

关于Scala - 处理 "multiple overloaded alternatives of method ... define default arguments",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30342253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com