scala - Scala 中简单表达式的非法开始

标签 scala syntax

我刚开始学习scala。我在 Eclipse 中尝试实现递归函数时遇到错误“简单表达式的非法开始”:

def foo(total: Int, nums: List[Int]): 
  if(total % nums.sorted.head != 0)
    0
  else 
    recur(total, nums.sorted.reverse, 0)

def recur(total: Int, nums: List[Int], index: Int): Int =
  var sum = 0 // ***** This line complained "illegal start of simple expression"
              // ... other codes unrelated to the question. A return value is included.

谁能告诉我在(递归)函数中定义变量时我做错了什么?我在网上进行了搜索,但无法解释此错误。

最佳答案

变量声明 ( var ) 不返回值,因此您需要以某种方式返回值,代码如下所示:

object Main {

  def foo(total: Int, coins: List[Int]): Int = {

    if (total % coins.sorted.head != 0)
      0
    else
      recur(total, coins.sorted.reverse, 0)

    def recur(total: Int, coins: List[Int], index: Int): Int = {
      var sum = 0
      sum
    }

  }


}

关于scala - Scala 中简单表达式的非法开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15962563/

相关文章:

scala - 在SBT项目中设置多个测试文件夹

Scala 检查 Future[Seq[String]] 是否为空

Ruby:定义使用语法糖的方法时的奇怪行为

mysql - 触发器中的更新语法错误

c - 包含数组下标的表达式可以是标识符吗?

scala - 线程 "main"java.lang.NoClassDefFoundError : org/rogach/scallop/ScallopConf 中的异常

scala - 用 For Comprehension 组合 Futures

java - 在 Circe 中处理不同数据类型的 json

syntax - Knockout.js 无容器 "foreach"不适用于 <table>

mysql - 帮我恢复数据库