You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala枚举转Map报错:无法证明enumeration.PhsIndType.Value <:< (AnyVal, AnyVal)

Fixing the Scala Enumeration to Map Conversion Error

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:35:28