\$\begingroup\$
\$\endgroup\$
I've just implement direction enum
object Direction extends Enumeration {
type Direction = Value
val Up, Right, Down, Left = Value
val pairs = HashSet() ++ List((HashSet() ++ List(Up, Down)), (HashSet() ++ List(Right, Left)))
def isOpposite(one: Direction, other: Direction): Boolean = {
pairs.contains(HashSet() ++ List(one, other))
}
}
Usages
direction match {
case Right => ...
case Left => ...
case Up => ...
case Down => ...
}
if(Direction.isOpposite(d1, d2))...
Can I improve it some how?
asked Dec 4, 2011 at 18:03
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
Use an Algebraic Data Type (ADT):
abstract class Direction(val opposite: Direction)
case object Up extends Direction(Down)
case object Down extends Direction(Up)
case object Left extends Direction(Right)
case object Right extends Direction(Left)
or:
abstract class Direction {
def isOpposite(d: Direction): Boolean
}
case object Up extends Direction {
def isOpposite(d: Direction) = d == Down
}
case object Down extends Direction {
def isOpposite(d: Direction) = d == Up
}
case object Left extends Direction {
def isOpposite(d: Direction) = d == Right
}
case object Right extends Direction {
def isOpposite(d: Direction) = d == Left
}
answered Dec 4, 2011 at 19:09
lang-scala