2

I have the following Scala enum which I designed after reading this answer:

object RunMode extends Enumeration {
    val CLIENT_MODE = Value("CLIENT_MODE")
    val SERVER_MODE = Value("SERVER_MODE")
}

I am now trying to pass an instance of it as an argument into the constructor of another class:

package com.me.myapp.shared.config

import com.me.myapp.shared.utils.RunMode

class MyAppConfig(runMode : RunMode) {

}

This gives me a compiler error:

Cannot resolve symbol RunMode

BTW: com.me.myapp.shared.utils.RunMode is the correct package path for RunMode, so that's not the issue here!

I assume that this is maybe because there is only (ever) one single instance of the RunMode object, and perhaps that prevents it from being passed in as an arg.

Either way, I don't really care what the solution is. But I need an "enum" called RunMode and I'll need to be able to pass instances of it into contructors of other classes. Any ideas?

Community
  • 1
  • 1
smeeb
  • 27,777
  • 57
  • 250
  • 447
  • I've written a small overview about scala Enumeration and alternatives, you may find it useful: pedrorijo.com/blog/scala-enums/ and http://pedrorijo.com/blog/scala-enums-part2/ – pedrorijo91 Mar 12 '17 at 13:34

2 Answers2

3

You are almost there, the correct type for a value of an Enumeration is Enumeration.Value, so here you need to use:

class MyAppConfig(runMode : RunMode.Value) {

}
vdebergue
  • 2,354
  • 16
  • 19
3

You're correct in the assumption that the only instance that inhabits the type RunMode is the object itself.

However fixing your problem isn't all that difficult.

object RunMode extends Enumeration {
  type RunMode = Value
  val CLIENT_MODE = Value("CLIENT_MODE")
  val SERVER_MODE = Value("SERVER_MODE")
}

The Enumeration class gives you the type Value which is the type that all of your enumerated types should have. It's scoped to the class instance, so every instance of Enumeration get's its own Value type.

You can give it a proper name by creating a type alias. Then you can import the inner type alias like this:

import com.me.myapp.shared.utils.RunMode._

And then you can pass Instances of your Enumeration around, therefore also allowing you to keep the MyAppConfig the same as it is right now.

Alternatively, you could of course also omit the type alias and just change the type signature of MyAppConfig to RunMode.Value. However I believe the former method is much better at clarifying intent.

class MyAppConfig(runMode: RunMode.Value) {

}
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57