scala - 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"
解决方案
我能够通过将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]()
}
}
推荐阅读
- fortran - 如何在fortran给定均值和标准差的情况下从fortran中的正态分布中随机生成数字
- scala - 通过 .filter 或 create 方法在 RDD 中添加元素?
- php - 将 Wordpress“wp-admin”仪表板隐藏到用户 ID
- c++ - 如何在特定位置推回没有大小的向量?
- servicenow - SERVICENOW - 使用查询结果填充字段
- reactjs - Jest - 模拟函数,从另一个文件导入
- javascript - 赛普拉斯断言 .should() 失败
- java - 以编程方式使用以下 java 代码创建附加程序,我需要使用我的 partternLayout 添加 MDC
- python - 如何在python中换行?
- python - 被杀死的子进程没有标准输出