OscarRyz OscarRyz - 1 month ago 8
Scala Question

How to return a function in scala

How can I return a function side-effecting lexical closure1 in Scala?

For instance, I was looking at this code sample in Go:

...
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return b
}
}
...
println(f(), f(), f(), f(), f())


prints
1 2 3 5 8

And I can't figure out how to write the same in Scala.

1. Corrected after Apocalisp comment

Answer

Slightly shorter, you don't need the return.

def fib() = {
    var a = 0
    var b = 1
    () => { 
        val t = a;
        a = b
        b = t + b
        b
    }
}