【问题标题】:Scala prevent mixing methodsScala 防止混合方法
【发布时间】:2014-01-26 17:50:24
【问题描述】:

我想创建以下特征:

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

返回

(2, 3, 4, 5, 10, 15, 20, 25, 12, 18, 24, 30, 14, 21, 28, 35)

但我不希望案例类中的 toString 方法被可遍历的方法之一覆盖!我该如何克服呢?

我希望最终输出是:

"AProduct(List(1, 5,6,7), List(2,3,4,5))"

如果可能的话,我想在 IntSet 中做以下事情:

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

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

【问题讨论】:

    标签: scala overriding tostring traversable


    【解决方案1】:

    您不需要在AProduct 中实现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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多