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

标签 scala scala-2.11

关于如何在不作弊和不使用 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/

相关文章:

scala - 从 scala 2.8.1 到 scala 2.9.1 的主要变化是什么?

postgresql - 光滑的 native 查询分页

java - 使用最新版本的 Scala 会出现 java.lang.ClassNotFoundException : scala. Function1$class

scala - 如何在 scala 枚举值中添加点

scala - 为什么通过 jenkins 用户在构建从站上运行测试失败并缺少 scala-library.jar?

scala - Scala案例类命名参数

scala - Raku 中的模式匹配是否有保护条款?

Scala 从 String 类名实例化对象

java - 如何为 Java 8 LocalDateTime 编写自定义序列化器

scala - 你如何缩进scaladoc的代码块