在 Scala 中创建使用枚举作为键的 Map 的语法是什么? [英] What is the syntax for creating a Map in Scala that uses an enum as a key?

查看:44
本文介绍了在 Scala 中创建使用枚举作为键的 Map 的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码.这一行被 Eclipse 标记为不正确:

please see the below code. This line is marked as incorrect by Eclipse:

var map = Map[MyEnum,Point]()

我正在尝试做 Java 的 Scala 等价物:

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()) ) 
}

我正在尝试初始化映射实例,将枚举的每个值映射到一个空点(这就是 for each 循环中发生的事情).

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).

不得不编辑,因为我在编辑粘贴的代码时搞砸了一些事情,但现在应该有效

推荐答案

var map = Map[MyEnum.Value, Point]()

或者我更喜欢

import MyEnum._
var map = Map[MyEnum,Point]()

edit: 为了稍微解释一下这意味着什么,在枚举中 Value 是类型和方法的名称.type MyEnum = Value 基本上只是为 Value 类型声明一个别名,下一行 val UL, U... = Value 是调用方法生成枚举,每个枚举的类型为 MyEnum.Value.因此,在声明映射时,您必须引用此类型以便键存储枚举.您也可以使用 MyEnum.MyEnum,但首先声明类型别名的原因是您可以将其导入作用域并能够像 MyEnum.

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.

这篇关于在 Scala 中创建使用枚举作为键的 Map 的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆