Question

Is there any logical reason why null.asInstanceOf[<some CPS annotated type>] fails to compile?

For context, see this github issue thread.

Was it helpful?

Solution

I wonder if the scala 2.9 version was doing the right thing even if it compiled (I'll try when I have a chance). Anyway, in 2.10.0 this compiles and works:

import scala.util.continuations._
object NullCPS extends App {
  def f[A,C] = shiftUnit[A,C,C](null.asInstanceOf[A])
  println(reset{"got " + f[Object, String]})  // prints: got null
  println(reset{"got " + f[Int, String]})     // got 0
  println(reset{"got " + f[Boolean, String]}) // got false   
}

shitUnit[A,B,C] is a library method from the continuations package that uses a value of type A to create a trivial ControlContext[A,B,C] expected to be used by a continuation k of type A=>B eventually returning a result of type C.

In my example above "got " + f[Object, String], the continuation plugin further composes the trivial null value with the (x:Object) => "got " + x function.

Moving on to the context of the question, I cannot see how Defaultable[T] can represent the T@cps[U] since it only has one type parameter. But if you enhance Defaultable:

import scala.util.continuations._
trait DefCPS[A,C] { def default: A@cps[C] }
object NullCPS extends App {
  implicit def defaultCPS[A,C] = new DefCPS[A,C] {
    def default: A@cps[C] = shiftUnit[A,C,C](null.asInstanceOf[A])
  }
  println(reset{"got " + implicitly[DefCPS[Object,String]].default})
  println(reset{"got " + implicitly[DefCPS[Int,String]].default})
  println(reset{"got " + implicitly[DefCPS[Boolean,String]].default})
}
// prints got null
//        got 0
//        got false

Notes: I had to make the trait use a def instead of val or it would not compile. I also tried materializing a A@cpsParam[B,C] but was not able.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top