gpt4 book ai didi

scala - 模式匹配依赖类型 - 如何避免 asInstanceOf?

转载 作者:行者123 更新时间:2023-12-03 19:07:05 28 4
gpt4 key购买 nike

关于如何在不作弊和不使用 asInstanceOf 的情况下完成以下操作,我画了一个空白.

假设我有一些任意密封类型的对象,每个对象都有自己的类型成员。

  sealed trait Part { type A }
case object P1 extends Part { override type A = String }
case object P2 extends Part { override type A = Int }

现在说我将 P 和 P.A 值捆绑在一起......
  trait PartAndA {
val p: Part
val a: p.A
}

object PartAndA {
type Aux[P <: Part] = PartAndA {val p: P}

def apply(_p: Part)(_a: _p.A): Aux[_p.type] =
new PartAndA {
override val p: _p.type = _p
override val a = _a
}
}

如何通过疲劳检查和没有手动转换的方式安全地完成以下任务?
  def fold[A](pa: PartAndA)(p1: PartAndA.Aux[P1.type] => A,
p2: PartAndA.Aux[P2.type] => A): A =
pa.p match {
case P1 => p1(pa.asInstanceOf[PartAndA.Aux[P1.type]])
case P2 => p2(pa.asInstanceOf[PartAndA.Aux[P2.type]])
}

最佳答案

我认为您的问题与 jvm type erasure 有关.没有它,您的问题可以简化为:

sealed trait Part { type A }
case class P1() extends Part { override type A = String }
case class P2() extends Part { override type A = Int }

trait PartAndA[P <: Part] {
val p: P
val a: p.A
}

object PartAndA {
type Aux[P <: Part] = PartAndA[P]

def apply(_p: Part)(_a: _p.A): PartAndA[_p.type] =
new PartAndA[_p.type] {
override val p: _p.type = _p
override val a = _a
}
}

def fold[A, T: ClassTag](pa: PartAndA[T])(p1: PartAndA[P1] => A,
p2: PartAndA[P2] => A): A =
pa match {
case s: PartAndA[P1] => p1(pa) // here P1 is lost, err
case i: PartAndA[P2] => p2(pa) // here P2 is lost, err
}

据我所知,没有更短的(比你的或 typeTags/classTags )jvm 类型删除的解决方法。

关于scala - 模式匹配依赖类型 - 如何避免 asInstanceOf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30935290/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com