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?

asked Dec 4, 2011 at 18:03
\$\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
}
answered Dec 4, 2011 at 19:09
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.