2

The extensible Enum pattern is relatively common but as I understand it neither Scala or Jave Enums are extensible. What's currently the best way to implement the extensible Enum pattern in Scala? So far using objects rather than Scala Enums or Java Enums, I have come up with the following:

trait TerrHexStd

import pEdit.TerrHexE
import pReal.TerrHexR
object TerrPlain extends TerrHexE with TerrHexR    
object TerrForrest extends TerrHexE with TerrHexR
object TerrHill extends TerrHexE with TerrHexR
object TerrMountain extends TerrHexE with TerrHexR
object TerrDesert extends TerrHexE with TerrHexR
object TerrRiver extends TerrHexE with TerrHexR
object TerrSea extends TerrHexE with TerrHexR

trait TerrHexE extends TerrHexStd //in separate package

object TerrUndef extends TerrHexE

trait TerrHexR extends TerrHexStd // in another separate package   

This is pretty horrible. But it is at least DRY.

I have edited my code for clarification of the problem.

3
  • You may simplify looks by replacing trait TerrHexStd with case class TerrHexStd(colour : ColorInt), replace object definitions with vals and place them inside an object ColorSet to import them all in one call import ColorSet._. Would such substitution provide tolerable verbosity level for you? Commented Mar 14, 2014 at 14:29
  • @ayvango I have edited my code to clarify the problem, sorry if that was unclear before. Commented Mar 14, 2014 at 15:21
  • Unfortunately, Scala enum-like functionality can be pretty horrible syntax-wise. Commented Mar 14, 2014 at 15:43

1 Answer 1

1

Usually when using scala objects for Enum's I'd do something like:

sealed abstract class Color(val name:String)
object Color {
  case object Blue extends Color("blue")
  case object Green extends Color("green")
  //...etc
}

With "sealed," you can match on the Enums without providing a default case, and without getting "match is not exhaustive" warnings. Sealed prevents other instances of the enumeration outside of the file in which it is defined, and usually you want to constrain how many values an enum has. The cross-package definition of the enum in your example seems a bit strange to me.

The companion object avoids polluting the namespace with your Enums.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.