简体   繁体   中英

Scala: Anonymous function return type

Why do i have to declare the return type this way:

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

If i remove the type, i'd have to assign it before printing:

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

this variant gives an error - why?

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

I get the following error (using Scala-ide):

recursive value n needs type Test.scala /src line 5 Scala Problem

You are seeing a problem with semicolon inference, due to the use of a postfix operator ( 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))

Essentially, Scala gets confused as to where an expression ends, so you need to be a little more explicit, one way or another.

Depending on compiler settings, this feature may be disabled by default - see Scala's "postfix ops" and SIP-18: Modularizing Language Features

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM