Reputation: 378
I currently have:
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(_))
}
I use it like 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)
}
It works like this:
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))
}
I want Z
to be simpler so that I can use M
like:
class Z extends M[Y] {
def apply(x: Int) = new Y(0.0, 0.0)
}
or, even better:
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]
}
Here are my Gist iterations to reach this point.
Upvotes: 2
Views: 323
Reputation: 39577
A third way in type params vs type members is to use both.
An advantage of a type member is that it doesn't pollute the signature of child classes. The type member can remain abstract if it is superfluous (even in a concrete class); and only the bottom class must define it if necessary.
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)
Upvotes: 2
Reputation: 6920
You didn't really need class M
here:
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))
If you want to keep M
, you use same idea:
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))
Upvotes: 1