문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top