Vote count:
0
Let's say I have a type Pos
(for position). In order to gain type-safety the column/row is not represented as Int
but by types Col
(column) and a Row
:
case class Pos(col: Col, row: Row) {
def +(other: Pos): Pos = Pos(col + other.col, row + other.row)
}
It's possible to add two positions, which consists of summing columns and rows respectively.
The definition of types Col
and Row
would look like this:
object Row {
def apply(value: Int) = new Row(value)
val zero = new Row(0)
}
object Col {
def apply(value: Int) = new Col(value)
val zero = new Col(0)
}
class Row(val value: Int) extends AnyVal {
def +(other: Row): Row = Row(this.value + other.value)
}
class Col(val value: Int) extends AnyVal {
def +(other: Col): Col = Col(this.value + other.value)
}
This is all fine, but I have the feeling of repeating myself. The definitions are almost identical.
Could I do something to generalize them?
asked 23 secs ago
Generic value-classes in Scala
Aucun commentaire:
Enregistrer un commentaire