HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Scala Direction enum with Enumeration and collection usage

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
enumerationdirectionenumwithcollectionscalausageand

Problem

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?

Solution

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
}

Code Snippets

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)
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
}

Context

StackExchange Code Review Q#6529, answer score: 4

Revisions (0)

No revisions yet.