3
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.