Scala <控制台>:1:错误:';' 预期但 '(' 发现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14373681/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:50:50  来源:igfitidea点击:

Scala <console>:1: error: ';' expected but '(' found

scala

提问by Anas

I keep getting this error when writing a simple recursive function in Scala. What am I missing?

在 Scala 中编写简单的递归函数时,我不断收到此错误。我错过了什么?

scala> def count(n1:Int, n1:Int) : List[Int] = (n1 < n2) ? List() : List(n1, count((n1 - 1), n2))
<console>:1: error: ';' expected but '(' found.
   def count(n1:Int, n1:Int) : List[Int] = (n1 < n2) ? List() : List(n1, count((n1 - 1), n2))

回答by Brian

In Scala the ternary operator is if. So, ?and :can be replaced with the usual ifand elsekeywords.

在 Scala 中,三元运算符是if。所以,?and:可以替换为常用的ifelse关键字。

Also, where is n2defined? I'll guess in countlike this def count(n1:Int, n2:Int) : List[Int] = ...

另外,在哪里n2定义?我想在count这样的def count(n1:Int, n2:Int) : List[Int] = ...

回答by korefn

This works!

这有效!

def count(n1:Int, n2:Int) : List[Int] = if (n1 < n2) List() else n1 :: count((n1 - 1), n2))

def count(n1:Int, n2:Int) : List[Int] = if (n1 < n2) List() else n1 :: count((n1 - 1), n2))

change count(n1:Int, n1:Int)to count(n1:Int,n2)The rest is adding an if elseclause instead of the ternary oprator.

更改count(n1:Int, n1:Int)count(n1:Int,n2)其余的是添加一个if else子句而不是三元运算符。

A similar code for doing this would be def count(n1:Int, n2:Int) = (n1 to n2).reverse

执行此操作的类似代码是 def count(n1:Int, n2:Int) = (n1 to n2).reverse