please see the below code. This line is marked as incorrect by Eclipse:
var map = Map[MyEnum,Point]()
I am trying to do the scala equivalent of Java:
private enum Letters{ A,B,C}
private Map<Letters,Integer> thing= new HashMap<Letters,Integer> ();
And this is the file/context in which it is written.
class Point(var x:Int = 0, var y:Int = 0, var hasBeenSet:Boolean = false){
}
object MyEnum extends Enumeration{
MyEnum = Value
val UL,U,UR,L,R,DL,D,DR = Value
}
object MyEnumHolder {
var map = Map[MyEnum,Point]()
MyEnum.values.foreach(x => (map + (x -> new Point()) )
}
I am trying to initialize an instance of the map with each value of the enum mapped to an empty point (that's what is going on in the for each loop).
EDIT: Had to edit because I messed some things up editing the pasted code, but it should be valid now
In HashMap, we can use Enum as well as any other object as a key.
In Scala, there is no enum keyword unlike Java or C. Scala provides an Enumeration class which we can extend in order to create our enumerations. Every Enumeration constant represents an object of type Enumeration. Enumeration values are defined as val members of the evaluation.
Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable. Map. While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable.
var map = Map[MyEnum.Value, Point]()
or I prefer
import MyEnum._
var map = Map[MyEnum,Point]()
edit: To give a little explanation of what this means, in the enumeration Value
is the name of both a type and a method. type MyEnum = Value
is basically just declaring an alias for the Value
type, and the next line val UL, U... = Value
is calling the method to generate the enums, each of which has type MyEnum.Value
. So when declaring the map, you have to refer to this type in order for the key to store enums. You could also use MyEnum.MyEnum
, but the reason you declare the type alias in the first place is so you can import it into scope and be able to refer to it just as MyEnum
.
You are not putting MyEnums
in the map, but values of MyEnum
:
var map = Map[MyEnum.Value, Point]()
object MyEnum extends Enumeration {
type MyEnum = Value /* You were missing keyword "type" here */
val UL,U,UR,L,R,DL,D,DR = Value
}
object MyEnumHolder {
import MyEnum.MyEnum /* Import this, otherwise type MyEnum can't be found */
var map = Map[MyEnum, String]()
MyEnum.values.foreach(x => (map + (x -> x.toString)))
}
You might also want to have a look at Case classes vs Enumerations in Scala.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With