【问题标题】:Scala <console>:1: error: ';' expected but '(' found斯卡拉 <console>:1: 错误: ';'预期但 '(' 找到
【发布时间】:2013-01-17 06:57:25
【问题描述】:

在 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))

【问题讨论】:

标签: scala


【解决方案1】:

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

另外,n2 是在哪里定义的?我猜countlike this def count(n1:Int, n2:Int) : List[Int] = ...

【讨论】:

  • n2 只是一个错字。我将运算符更改为if,现在又出现了另一个错误。 ` :1: 错误:非法开始简单表达式 def count (n1:Int, n2:Int) : List[Int] = def count (n1:Int, n2:Int) : List[Int] = if ( n1
  • 您评论中的代码已经定义了两次def count (n1:Int, n2:Int) : List[Int] =
【解决方案2】:

这行得通!

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

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

类似的代码是def count(n1:Int, n2:Int) = (n1 to n2).reverse

【讨论】:

  • 谢谢用if else 替换它并且它工作,认为这在 scala 上得到支持
  • 由于if else 工作并返回,“不需要”三元运算符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2019-01-11
  • 1970-01-01
  • 2012-03-17
  • 2017-08-22
相关资源
最近更新 更多