这个非编译代码定义递归函数值
val factorial = (n:Int) => if (n < 1) 1 else n * factorial(n-1)
会生成错误消息,例如
recursive value factorial needs type
如何声明返回类型?
答案 0 :(得分:8)
喜欢这个
val factorial: Int => Int = (n:Int) => if (n<1) 1 else n*factorial(n-1)
事实上,我会这样写:
def factorial(n: Int): Int = if (n < 1) 1 else n * factorial(n-1)
答案 1 :(得分:3)
val factorial: Int => Int = (n) => if (n<1) 1 else n*factorial(n-1)