标量延续未编译

问题描述 投票:2回答:1

我正在尝试使用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]如果(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"
scala continuations
1个回答
0
投票

通过将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]()
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.