1

in java i've got enum say

enum Num {
    ONE,
    TWO,
    THREE;

    private static Num current = ONE;
    private static Num next = TWO;

    public Num getNext(){
        return values()[(ordinal() + 1) % values().length];
    }

    public static Num getNextNum(){
       next = current.getNext()
    }
}

so i'm able to assign next in that fashion calling getNextNum(), but scala enums, as it seems to me, lacks this feature. do u know any other workaround except using java enum in scala code?

Dmitrii
  • 604
  • 2
  • 9
  • 30

2 Answers2

2

Take a look at Case objects vs Enumerations in Scala

In Scala, Enumeration has limited functionality and it's preferable to have sealed traits if you want to have functionality added to your Enumeration. For example:

sealed trait Num {
  val next: Num
}
case object ONE extends Num {
  override val next = TWO
}
case object TWO extends Num {
  override val next = THREE
}
case object THREE extends Num {
  override lazy val next = ONE
}

Also in your case, it's a bit tricky since you want to refer to a value before it's initialized. So there is a lazy on the last definition (you can also define next as def, if you want to)

Community
  • 1
  • 1
mavarazy
  • 7,562
  • 1
  • 34
  • 60
2

In case you wanted to achieve this behavior using standard Scala Enumeration, you can redefine Enumeration#Value as instances of your enum:

object Num extends Enumeration {
  case class MyValue() extends Val {
    def next: MyValue = Num((id + 1) % Num.values.size).asInstanceOf[MyValue]
  }
  val One, Two, Three = MyValue()
}

Num.One.next
// res0: Num.MyValue = Two

However, since Enumerations are bad due to so many reasons, as well as don't have consistent IDE support, I personally would use sealed traits with case objects for enums (check out enumeratum) which allow to introduce arbitrary logic for my enums due to precise control over what's going on.

Sergey
  • 2,880
  • 3
  • 19
  • 29
  • that's what i'm looking for, but when i'm trying to change var current = current.next, it says that requiring type is MyValue.type buy the one it gets is Num.MyValue. – Dmitrii Jun 22 '16 at 19:50