2

我目前有:

class X[+T: Numeric](val x: T)
abstract class M[N: Numeric, T <: X[N]] { // <- I'd like to remove N.
  def apply(x: Int): T
  final def row = (1 to 10).map(this(_))
}

我这样使用它:

class Y(x: Double, val y: Double) extends X[Double](x)
class Z extends M[Double, Y] {           // <- So that this is simpler.
  def apply(x: Int) = new Y(0.0, 0.0)
}

它是这样工作的:

object testapp {
  // row is properly polymorphic, allowing access to Y.y
  def main(args: Array[String]): Unit = (new Z).row.map(r => println(r.y))
}

我想Z更简单,以便我可以使用M

class Z extends M[Y] {
  def apply(x: Int) = new Y(0.0, 0.0)
}

或者,甚至更好:

class Z extends M[Double] {           // i.e. Meaning apply can return
  def apply(x: Int) = new Y(0.0, 0.0) // any subclass of X[Double]
}

这是我达到这一点的要点迭代。

4

2 回答 2

2

类型参数与类型成员的第三种方法是同时使用两者。

类型成员的一个优点是它不会污染子类的签名。如果类型成员是多余的(即使在具体类中),则类型成员可以保持抽象;如果需要,只有底层必须定义它。

  import scala.collection.immutable.IndexedSeq
  class X[+T: Numeric](val x: T)
  abstract class M[+A: Numeric] {
    type W <: X[A]
    def apply(x: Int): W
    final def row: IndexedSeq[W] = (1 to 10) map apply
    def sumx: A = {  // in terms of the underlying Numeric
      val n = implicitly[Numeric[A]]
      n fromInt (0 /: row)((s,w) => s + (n toInt w.x))
    }
  }

  class Y(x: Double, val y: Double) extends X[Double](x)
  class Z extends M[Double] {
    type W = Y
    def apply(x: Int) = new Y(0.0, 0.0)
  }

  def main(args: Array[String]): Unit = (new Z).row foreach (Console println _.y)
于 2012-12-16T09:23:47.643 回答
1

你真的不需要class M这里:

class X[+T: Numeric](val x: T)
def row[W <: X[_]](c: => Int => W) = (1 to 10).map(c)

class Y(x: Double, val y: Double) extends X[Double](x)
def z = row(_ => new Y(0.0, 0.0))

def main(args: Array[String]): Unit = z.map(r => println(r.y))

如果你想保留M,你使用相同的想法:

class X[+T: Numeric](val x: T)
abstract class M[W <: X[_]] {
    def apply(x: Int): W
    final def row = (1 to 10).map(this(_))
}

class Y(x: Double, val y: Double) extends X[Double](x)
class Z extends M[Y] {
  def apply(x: Int) = new Y(0.0, 0.0)
}

def main(args: Array[String]): Unit = (new Z).row.map(r => println(r.y))
于 2012-12-16T02:46:41.803 回答