我想创建以下特征:
trait IntSet[A] extends Traversable[A] { self: Product =>
def foreach[U](f: A => U): Unit
}
case class AProduct(a: List[Int], b: List[Int]) extends IntSet[Int] {
def foreach[U](f: Int => U): Unit = {
for(aa <- a; bb <- b) f(aa*bb)
}
}
AProduct(List(1, 5,6,7), List(2,3,4,5)).toString
Run Code Online (Sandbox Code Playgroud)
回报
(2, 3, 4, 5, 10, 15, 20, 25, 12, 18, 24, 30, 14, 21, 28, 35)
Run Code Online (Sandbox Code Playgroud)
但我不希望case类中的toString方法被遍历的一个覆盖!我该如何克服这个问题?
我希望最终输出为:
"AProduct(List(1, 5,6,7), List(2,3,4,5))"
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想在IntSet中做以下的事情:
override def toString = this.getClass().getName()+"("+self.productIterator.mkString(",")+")"
Run Code Online (Sandbox Code Playgroud)
哪个有效,但我真的不想重新发明轮子.
class Bar { override def toString() = "Bar" }
case class Foo(s: String) extends Bar
Foo("bar") // "Bar"
Run Code Online (Sandbox Code Playgroud)
为什么不生成Foo它toString?这是一个错误还是实际上有原因?有没有办法"把它取回"(是否有一个默认的实现可能适用于案例类)?