Scala枚举转Map报错:无法证明enumeration.PhsIndType.Value <:< (AnyVal, AnyVal)
The error you're seeing happens because PhsIndType.values is an Iterable of your enum's Value instances, not a collection of key-value tuples. The toMap method requires elements to be in the form (KeyType, ValueType)—so we need to first transform each enum value into a tuple before converting to a map.
Here are a few common ways to create the map you need, depending on what key-value pairs you want:
1. Map from Enum Value to Its Numeric ID
If you want to map each enum instance to its underlying integer value (like A -> 1, R -> 2):
import PhsIndType._ val valueToIdMap: Map[PhsIndType.Value, Int] = PhsIndType.values.map(enumVal => enumVal -> enumVal.id).toMap
2. Map from Numeric ID to Enum Value
If you need the reverse mapping (like 1 -> A, 2 -> R):
import PhsIndType._ val idToValueMap: Map[Int, PhsIndType.Value] = PhsIndType.values.map(enumVal => enumVal.id -> enumVal).toMap
3. Map from Enum Name (String) to Enum Value
If you want to map the string name of each enum (like "A" -> A, "R" -> R):
import PhsIndType._ val nameToValueMap: Map[String, PhsIndType.Value] = PhsIndType.values.map(enumVal => enumVal.toString -> enumVal).toMap
Why This Works
By calling map on PhsIndType.values, we convert each Value instance into a tuple (either (Value, Int), (Int, Value), or (String, Value)). Once we have an Iterable of tuples, the toMap method can correctly infer the key and value types and create the desired map without type errors.
内容的提问来源于stack exchange,提问作者Martin Remy

