函数签名与函数调用匹配时,Scala类型不匹配错误

时间:2013-10-04 18:56:33

标签: scala

我对Scala很新,但我相信我已经编写了一个完全合法的Scala程序:

这是在Scala工作表上:

  def product(f: Int => Int)(a: Int, b: Int): Int =
    if (a > b) 1 // Not a 0 because the unit value of product is a 1
    else f(a) * product(f)(a + 1, b)

  product(x => x * x)(3, 7)

但是,我收到以下错误:

> <console>:8: error: type mismatch;
   found   : Unit
   required: Int
           if (a > b) 1 // Not a 0 because the unit value of product is a 1 else f
  (a) * product(f)(a + 1, b)
           ^
> <console>:8: error: not found: value product
                product(x => x * x)(3, 7)
                ^

这是一个简单的产品,可以将所有数字的平方从a增加到b

它说我的函数调用了一些东西,但是,这应该是完全合法的,因为我传递的lambda函数确实返回Int。有关此问题以及如何处理type mismatch错误的任何帮助都将深表感谢。

使用Scala 2.10.2

3 个答案:

答案 0 :(得分:3)

工作表以某种方式将product的主体分成一行,因此else子句不存在。您的代码将在repl中编译并运行。

答案 1 :(得分:1)

尝试在方法体周围放置大括号:

def product(f: Int => Int)(a: Int, b: Int): Int = {
  if (a > b) 1
  else f(a) * product(f)(a + 1, b)
}
product(x => x * x)(3, 7)

为我工作。

答案 2 :(得分:0)

如果你使用repl,你应该将具体函数的主体括在这样的大括号中:

def product(f: Int => Int)(a: Int, b: Int): Int = {
    if (a > b) 1 // Not a 0 because the unit value of product is a 1
    else f(a) * product(f)(a + 1, b)
}

  product(x => x * x)(3, 7)

在其他情况下,scala repl只能看到这种函数的定义:

def product(f: Int => Int)(a: Int, b: Int): Int = if (a > b) 1

这是不正确的