首页 > 解决方案 > Scala 延续不编译

问题描述

我正在尝试 Scala 的延续库(使用 Scala 2.12.10)。我正在测试的代码 - 检查我是否理解这个概念 - 如下:

object Test {

  import scala.util.continuations._

  def run(): (Unit => Unit)  = {
    var x = 0;
    reset {
      while (x < 10) {
        if (x == 5)
          shift { cont: (Unit => Unit) =>
            return cont
          }
        println(f"x = $x")
        x += 1
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val cont = run()
    cont()
  }

}

我正在尝试的代码是为了打破while循环并允许调用者调用延续来恢复循环。但是,我收到一个错误:

错误:(9, 9) 类型不匹配;发现:需要单位:单位
@scala.util.continuations.cpsParam[Unit,Nothing]
if (x == 5)

我怀疑我必须在@scala.util.continuations.cpsParam[Unit,Nothing]某个地方添加,但是在随机位置尝试之后,我不知道它应该放在哪里。如何更正我的代码以便编译?

我的build.sbt

name := "continuations"

version := "0.1"

scalaVersion := "2.12.10"

autoCompilerPlugins := true


libraryDependencies +=
  "org.scala-lang.plugins" %% "scala-continuations-library" % "1.0.3"

addCompilerPlugin(
"org.scala-lang.plugins" % "scala-continuations-plugin_2.12.0" % "1.0.3")
scalacOptions += "-P:continuations:enable"

标签: scalacontinuations

解决方案


我能够通过将else分支添加到 内部的条件reset并将返回类型设置为run来使代码工作Any。我认为问题与从内部不同代码分支返回的类型不一致有关run,但我真的不知道,是否有一个比Any这更具体的可以用来使事情正常工作。

object Test {

  import scala.util.continuations._

  def run():Any = {
    var x = 0;
    reset {

      while (x < 10) {
        if (x == 5)
          shift { cont: (Unit => Unit) =>
            return cont
          } else shift { cont: (Unit => Unit) =>
            cont()
          }
        println(f"x = $x")
        x += 1
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val cont = run()
    printf("Continuation called\n")
    cont.asInstanceOf[Unit=>Unit]()
  }

}

推荐阅读