Scala 中简单表达式的非法开始
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15962563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Illegal start of simple expression in Scala
提问by ChuanRocks
I just start learning scala. I got an error "illegal start of simple expression" in eclipse while trying to implement a recursive function:
我刚开始学习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.
Can anyone tell me what I did wrong about defining a variable inside a (recursive) function? I did a search online but can't one explains this error.
谁能告诉我在(递归)函数中定义变量时我做错了什么?我在网上进行了搜索,但无法解释此错误。
采纳答案by Maurício Linhares
A variable declaration (var) doesn't return a value, so you need to return a value somehow, here's how the code could look like:
变量声明 ( 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
}
}
}
回答by Daniel C. Sobral
The indentation seems to imply that recuris inside count, but since you did not place {and }surrounding it, countis just the if-else, and recuris just the var(which is illegal -- you have to return something).
缩进似乎暗示 that recuris inside count,但由于您没有放置{和}包围它,count因此只是 if-else,并且recur只是 the var(这是非法的 - 您必须返回一些东西)。
回答by Vito
I had a similar problem. Found example 8.1 in the book that looked like:
我有一个类似的问题。在书中找到示例 8.1,如下所示:
object LongLines {
def processFile(filename: String, width: Int) **{**
val source = Source.fromFile(filename)
for (line <- source.getLines)
processLine(filename, width, line)
**}**
Note: the "def processFile(filename: String, width: Int) {" and ending "}"
注意:“def processFile(filename: String, width: Int) {”和结尾的“}”
I surrounded the 'method' body with {} and scala compiled it with no error messages.
我用 {} 包围了“方法”主体,scala 编译了它,没有错误消息。

