Senthess
Senthess

Reputation: 17540

How is Scala inferring these two functions differently?

This compiles:

 def fibonacci():() => Int = {
        var first   = 1
        var second  = 2
        return () => {
            val oldFirst = first
            first = second
            second = second + oldFirst
            second 
        }
    }

This doesn't:

 def fibonacci():() => Int = {
     var first   = 1
     var second  = 2
     return ():Int => {
         val oldFirst = first
         first = second
         second = second + oldFirst
         second 
     }
 }

I am explicitly trying to tell it that I'm returning an Int, but I get this error: Illegal start of declaration, and it's pointing to the first = second line. How are they different? I am using Scala 2.8.1.

Upvotes: 1

Views: 162

Answers (2)

Kipton Barros
Kipton Barros

Reputation: 21112

Debilski is right. Two more comments: (1) The return keyword is not necessary. By default, the last expression becomes the return value. (2) If you're trying to annotate the type of the function body alone, that is possible. The code becomes:

def fibonacci2(): () => Int = {
  var first   = 1
  var second  = 2
  () => {
    val oldFirst = first
    first = second
    second = second + oldFirst
    second 
  }: Int
}

Upvotes: 6

Debilski
Debilski

Reputation: 67838

return (): Int => {...} is not a proper expression in Scala. If you wanted to specify the return type explicitly, you’ll need to put the declaration after the value (and the value would be the anonymous function):

def fibonacci():() => Int = {
  var first   = 1
  var second  = 2
  return ( () => {
    val oldFirst = first
    first = second
    second = second + oldFirst
    second 
  } ) : () => Int
}

Note, however, that there is no need in doing that. If you omit return, you do not need to make any explicit type declaration at all:

def fibonacci() = {
  var first   = 1
  var second  = 2
  () => {
    val oldFirst = first
    first = second
    second = second + oldFirst
    second 
  }
}

Upvotes: 8

Related Questions