如何使用多个参数列表消除案例类创建的歧义?

Sil*_*eak 5 scala currying

我有一个看起来像这样的案例类:

case class A(first: B*)(second: C*)
Run Code Online (Sandbox Code Playgroud)

这两个firstsecond重复,所以我把在不同的参数列表.但是,我希望second在很多情况下可能是空的,所以能够像A(???, ???)没有尾随空括号那样使用类就好了.我尝试了以下方法:

case class A(first: B*)(second: C*) {
  def this(first: B*) = this(first: _*)()
}
Run Code Online (Sandbox Code Playgroud)

哪能给我ambiguous reference to overloaded definition.

有没有办法明确地编写这个构造函数调用?(并且我能够调用重载的构造函数而不会再次混淆语法吗?)我的猜测是否定的,有一些关于这种语法糖会如何破坏currying或其他一些问题的争论,但我更愿意听到来自某人的声音比我更多Scala知识;)

Ben*_*ich 3

以下可能会实现您的目标:

case class Foo private(first: List[Int], second: List[Int])

object Foo {
    def apply(first: Int*) = new Foo(first.toList, List.empty[Int]) { 
        def apply(second: Int*) = new Foo(first.toList, second.toList)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

Foo(1, 2, 3)
Foo(1, 2, 3)(4, 5, 6)
Run Code Online (Sandbox Code Playgroud)

由@SillyFreak编辑:这个变体没有给出“结构类型成员的反射访问”警告,所以我认为它应该在性能方面更好一些:

case class Foo private (first: List[Int], second: List[Int])

object Foo {
  def apply(first: Int*) = new Foo(first.toList, List.empty[Int]) with NoSecond

  trait NoSecond {
    self: Foo =>
    def apply(second: Int*) = new Foo(first.toList, second.toList)
  }
}

Foo(1, 2, 3)
Foo(1, 2, 3)(4, 5, 6)
Run Code Online (Sandbox Code Playgroud)

  • 哇,现在太光滑了!我不知道您可以通过细化实例化“案例类”。我错误地认为“case class”暗示着“final”,但再次查找时,我发现情况并非如此。*并且*看来“unapply”仍然以合理的方式运行。做得好! (2认同)