2015-06-19 45 views
5

我在如何完成以下操作而沒有作弊和使用asInstanceOf上畫了一個空白。模式匹配依賴類型 - 如何避免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]]) 
    } 

回答

1

我認爲你的問題與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類型擦除的解決方法。

+0

啊是的,如果我在'pa'上匹配,那麼會是這種情況,但是'pa.p'是具體的,我們可以在沒有擦除問題的情況下進行匹配。我只是不知道如何構建一個證明,說如果我知道'pa.p'類型,那麼我知道'PartAndA.Aux'類型。 – Golly