What is the syntax for creating a Map in Scala that uses an enumeration as a key?

see below code. This line is marked as invalid by Eclipse:

var map = Map[MyEnum,Point]() 

I am trying to make the scala Java equivalent:

 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 a map instance with each enum value being mapped to an empty dot (which happens in every loop).

EDIT: I had to edit because I messed up some things by editing the inserted code, but it should be valid now

+6
source share
4 answers
 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, the Value enumeration contains the name of both the type and the method. type MyEnum = Value basically just declares an alias for the Value type, and the next line val UL, U... = Value calls a method to create enumerations, each of which is of type MyEnum.Value . Therefore, when declaring a card, you must refer to this type so that the key stores the transfers. You can also use MyEnum.MyEnum , but the reason you declare a type alias in the first place is because you can import it into the scope and be able to refer to it just like MyEnum .

+13
source

You do not put MyEnums on the map, but MyEnum values:

 var map = Map[MyEnum.Value, Point]() 
+2
source
 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 can also see class classes vs enums in Scala .

+2
source

I got it to work with the following. I agree that the syntax is a bit fired.

 object MyEnum extends Enumeration { type MyEnum = Value val UL, U, UR, L, R, DL, D, DR = Value } object Main extends App { Map[MyEnum.MyEnum, String]() } 

Although I think it can help for pluralization

 object Diaries extends Enumeration { type Diary = Value val Steven, Jessica, Bob = Value } import Diaries._ val currentDiary = Steven val interestingDiaries = List[Diary](Steven, Jessica) 

So, here the Diaries is a list of Diaries, and the Diary is a specific diary in the list.

+1
source

Source: https://habr.com/ru/post/920262/


All Articles