Scala阶乘语法错误

时间:2017-04-05 02:08:16

标签: scala factorial

我写了以下代码:

def factorial(x: Int, factorial( x => { if (x == 0) 1 else x * factorial(x - 1) })): Int = factorial(3)

但得到了错误:

<console>:1: error: ':' expected but '(' found.

2 个答案:

答案 0 :(得分:3)

这部分代码有意义(至少在句法上):

String

def factorial(...): Int = factorial(3) 中的内容是函数的参数。你使用...

开始了
x:Int

然而,它与def factorial(x: Int, ...): Int = factorial(3) 在语法上有所不同。我真的不知道该怎么说,除了它绝对不是函数论证。那是一个表达式,这是你放在函数体中的东西(在factorial(x=>{if(x==0)1 else x*factorial(x-1)})之后),而不是在参数列表中。

答案 1 :(得分:1)

您有factorial作为def的参数项,这是不正确的。尝试:

def factorial(x:Int): Int =
  if (x == 0) 1
  else x * factorial(x - 1)