Scala 3中如何替代已被移除的通用类型投影?
Scala 3 中正确定义 Dictionary 类型的方法
原代码在 Scala 3 中无法编译,是因为 Scala 3 移除了抽象类型参数上的类型投影(也就是T#Key这种写法,当T是抽象类型参数时不再合法)。下面提供两种常用的修复方案:
方案一:将 Entity 的类型成员改为类型参数
把Entity的Key类型成员换成类型参数,直接在Dictionary中引用该参数,避免类型投影:
// 重构 Entity,用类型参数替代类型成员 trait Entity[K]: // 可选:保留原类型成员以兼容依赖它的旧代码 type Key = K // 定义 Dictionary,明确绑定 K 和 T 的关系 type Dictionary[K, T <: Entity[K]] = Map[K, T]
使用示例:
case class User(id: String) extends Entity[String] // 此时 Dictionary[String, User] 等价于 Map[String, User] val userDict: Dictionary[String, User] = Map("1" -> User("1"))
方案二:保留 Entity 的类型成员,使用结构类型约束
如果不想修改Entity的定义,可通过结构类型约束T的Key类型,从而在Dictionary中合法引用:
// 保留原 Entity 定义不变 trait Entity: type Key // 用结构类型限定 T 的 Key 必须等于 K type Dictionary[K, T <: Entity { type Key = K }] = Map[K, T]
使用示例:
case class Order(orderNo: Long) extends Entity { type Key = Long } // Dictionary[Long, Order] 等价于 Map[Long, Order] val orderDict: Dictionary[Long, Order] = Map(1001L -> Order(1001L))
两种方案各有适用场景:方案一更简洁且类型检查更直接,适合新代码;方案二无需修改原有Entity结构,适合兼容旧代码场景。
内容的提问来源于stack exchange,提问作者Grégory Weinbach
相关产品推荐
相关产品推荐

