Scala防止混合方法

Scala防止混合方法,scala,overriding,tostring,traversable,Scala,Overriding,Tostring,Traversable,我想创造以下特质: 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 <

我想创造以下特质:

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
但是我不希望case类中的toString方法被可遍历的方法覆盖!我如何克服这一点

我希望最终输出为:

"AProduct(List(1, 5,6,7), List(2,3,4,5))"
如果可能,我想在IntSet中执行以下操作以外的操作:

override def toString = this.getClass().getName()+"("+self.productIterator.mkString(",")+")"

这是可行的,但我真的不想重新发明轮子。

您不需要在
产品中实现
IntSet
。您可以只添加所有不带继承的方法,如下所示:

case class AProduct(a: List[Int], b: List[Int])
object AProduct {
  implicit class AProductIntSet(p: AProduct) extends Traversable[Int] {
    def foreach[U](f: Int => U): Unit = {
      for(aa <- p.a; bb <- p.b) f(aa*bb)
    }
  }
}

val ap = AProduct(List(1, 5,6,7), List(2,3,4,5))
// AProduct = AProduct(List(1, 5, 6, 7),List(2, 3, 4, 5))

ap.toString
// String = AProduct(List(1, 5, 6, 7),List(2, 3, 4, 5))

ap.map{_ + 1}
// Traversable[Int] = List(3, 4, 5, 6, 11, 16, 21, 26, 13, 19, 25, 31, 15, 22, 29, 36)

for{i <- AProduct(List(2), List(3, 5))} println(i)
// 6
// 10
case类产品(a:List[Int],b:List[Int])
对象产品{
隐式类AProductIntSet(p:AProduct)扩展了可遍历的[Int]{
def foreach[U](f:Int=>U):单位={

对于(aa),我不知道您可以直接在companion中为类添加隐式。@MikaëlMayer:请参阅。companion对象始终在隐式搜索范围内。它非常有用。
case class AProduct(a: List[Int], b: List[Int])
object AProduct {
  implicit class AProductIntSet(p: AProduct) extends Traversable[Int] {
    def foreach[U](f: Int => U): Unit = {
      for(aa <- p.a; bb <- p.b) f(aa*bb)
    }
  }
}

val ap = AProduct(List(1, 5,6,7), List(2,3,4,5))
// AProduct = AProduct(List(1, 5, 6, 7),List(2, 3, 4, 5))

ap.toString
// String = AProduct(List(1, 5, 6, 7),List(2, 3, 4, 5))

ap.map{_ + 1}
// Traversable[Int] = List(3, 4, 5, 6, 11, 16, 21, 26, 13, 19, 25, 31, 15, 22, 29, 36)

for{i <- AProduct(List(2), List(3, 5))} println(i)
// 6
// 10