Scala Continuations - Why can't my shifted call be inside a try-catch block?

允我心安 提交于 2019-12-04 10:28:17

Thanks @som-snytt, but your solution was somewhat far from a generic one. I can't demand the framework user to write def my_check instead of val my_check every time it uses a try-catch block.

However, I played with your solution, and built the following code:

import scala.util.continuations._

case class MyException(msg:String) extends Exception

object try_protector {
  def apply[A,B](comp: => A @cps[B]):A @cps[B] = {
    comp
  }
}

object Test extends App {
  def go: Int = reset {
    println("enter your input")
    val my_check = try_protector { 
      try {
        val user_input = readLine()
        if (!user_input.matches("\\w+")) {
          throw new MyException("illegal string: " + user_input)
        }
        shift {
          k: (Boolean => Int) => {
            user_input match {
              case "true"   => k(true)
              case "false"  => k(false)
              case _        => 0
            }
          }
        }
      } catch {
        case MyException(msg) => false
      }
    }

    if (my_check) {
      println("TRUE")
      1
    } else {
      println("FALSE")
      -1
    }
  }
  println(go)
}

And it works! (on scala 2.9.2)

The user just has to wrap his try-catch block with a try_protector and the code will compile.

Don't ask me how or why... It looks like compilation VODOU to me...

I haven't tried it on scala 2.10.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!