Frage

I'm playing with path dependent types and become puzzled with a simple case where type inference could not help me and I have no idea how the type should be specified manually

final class Dependency[A]() {
  final case class Box protected[Dependency] (data : A)
  def box(data : A) : Box = Box(data)
  def unbox(box : Box) : A = box.data
}

def correct() {
  val dep = new Dependency[Int]
  val u = dep.box(0)
  val v = dep.unbox(u)
}

object InCorrect {
  def wrap(src : Int) = { // what return type should be here?
    val dep = new Dependency[Int]
    val box = dep.box(src)
    (dep, box)
  }
  def unwrap() {
    val (dep,box) = wrap(0)
    val v = dep.unbox(box) //type mismatch found
  }
}

I just split one function into two and type information gets lost somewhere between two calls. How can I reestablish it?

War es hilfreich?

Lösung

As for the return type:

def wrap(src: Int): (Dependency[Int], Dependency[Int]#Box) = {
  val dep = new Dependency[Int]
  val box = dep.box(src)
  (dep, box)
}

As for getting the values from the tuple:

def unwrap() = {
  val x = wrap(20)

  val (dep, _) = x
  val (_, box: dep.Box) = x

  val v = dep.unbox(box)
  v
}

So this workaround pulls out the first value, and uses the type thereof in a type ascription to get the second value.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top