scala“简单表达式的非法开始”用于if理解

66bbxpm5  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(230)

我正在实现一个简单的内存中的、类似redis的keyvalue存储,并且在理解以下代码时遇到了if语句的编译失败:

/*
  Returns the specified elements of the list stored at key. The offsets start and
  stop are zero-based indexes, with 0 being the first element of the list to n. */

  def lrange(k: keyT, maxIdx:Int, minIdx:Int): List[valT] = {
    val l = lookup(k)
    //assert(maxIdx >= minIdx && maxIdx <= (l length) && minIdx >= 0, "invalid min or max argument. list size ")
    for {
      (x: valT, i: Int) <- l zipWithIndex      //tried without explicit typing
      if i <= maxIdx && i >= minIdx            //tried indenting if
    } yield x
  }

编辑器(intellij)没有显示错误,但是我在尝试生成和运行测试时收到以下生成错误。

[INFO] --- scala-maven-plugin:3.3.2:compile (default) @ DS4300Project3 ---
[INFO] .../Spring2019/DS4300/scala/DS4300Project3/src/main/scala:-1: info: compiling
[INFO] Compiling 3 source files to .../Spring2019/DS4300/scala/DS4300Project3/target/classes at 1550678144065
[ERROR] .../Spring2019/DS4300/scala/DS4300Project3/src/main/scala/com/rejevichb/homework3/KeyValStore.scala:70: error: illegal start of simple expression
[ERROR]       if (i <= maxIdx) && (i >= minIdx) //tried indenting if
[ERROR]       ^
[ERROR] one error found
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

明确地:

KeyValStore.scala:70: error: illegal start of simple expression

任何指导或洞察什么是错在这里是赞赏的,因为解决办法是不清楚的我。

k3fezbri

k3fezbri1#

这正是您应该谨慎使用后缀运算符的原因。

for {
  i <- "a" zipWithIndex
  if true
} yield i

解析为

for { i <- ("a" zipWithIndex if true) } yield i

因为编译器试图解释 zipWithIndex 作为一个二进制中缀运算符,但是 if true ,这确实不是一个简单的表达。
解决方法:
只是不要使用后缀操作,使用句点:

for {
  i <- "a".zipWithIndex
  if true
} yield i

添加分号以强制 zipWithIndex 解释为后缀op:

for {
  i <- "a" zipWithIndex;
  if true
} yield i

然后享受您的功能警告:
警告:应通过使隐式值scala.language.postfix可见来启用后缀运算符zipwithindex。

相关问题