Scala:匿名函数返回类型

时间:2014-04-15 11:22:24

标签: function scala types return anonymous

为什么我必须以这种方式声明返回类型:

def main(args: Array[String]): Unit = {
  val n = (x: Int) => (1 to x) product: Int
  println(n(5))
}

如果我删除了类型,我必须在打印之前分配它:

def main(args: Array[String]): Unit = {
  val n = (x: Int) => (1 to x) product
  val a = n(5)
  println(n(5))
}

此变体出错 - 为什么?

val n = (x: Int) => (1 to x) product
println(n(5))

我收到以下错误(使用Scala-ide):

  

递归值n需要类型Test.scala / src第5行Scala问题

1 个答案:

答案 0 :(得分:3)

由于使用了后缀运算符(product),您看到分号推断出现问题:

// Error
val n = (x: Int) => (1 to x) product
println(n(5))

// OK - explicit semicolon
val n = (x: Int) => (1 to x) product;
println(n(5))

// OK - explicit method call instead of postfix - I prefer this one
val n = (x: Int) => (1 to x).product
println(n(5))

// OK - note the newline, but I wouldn't recommend this solution!
val n = (x: Int) => (1 to x) product

println(n(5))

基本上,Scala对于表达式结束的位置感到困惑,所以你需要更加明确,不管怎样。

根据编译器设置,默认情况下可能会禁用此功能 - 请参阅Scala's "postfix ops"SIP-18: Modularizing Language Features