我有一个看起来像这样的案例类:
case class A(first: B*)(second: C*)
这两个first和second重复,所以我把在不同的参数列表.但是,我希望second在很多情况下可能是空的,所以能够像A(???, ???)没有尾随空括号那样使用类就好了.我尝试了以下方法:
case class A(first: B*)(second: C*) {
  def this(first: B*) = this(first: _*)()
}
哪能给我ambiguous reference to overloaded definition.
有没有办法明确地编写这个构造函数调用?(并且我能够调用重载的构造函数而不会再次混淆语法吗?)我的猜测是否定的,有一些关于这种语法糖会如何破坏currying或其他一些问题的争论,但我更愿意听到来自某人的声音比我更多Scala知识;)
以下可能会实现您的目标:
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)
    }
}
然后你可以这样做:
Foo(1, 2, 3)
Foo(1, 2, 3)(4, 5, 6)
由@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)
| 归档时间: | 
 | 
| 查看次数: | 781 次 | 
| 最近记录: |