How to return a function in scala

前端 未结 5 1056
忘了有多久
忘了有多久 2021-02-02 14:31

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

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

5条回答
  •  猫巷女王i
    2021-02-02 15:07

    Got it!! after some trial and error:

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

    Testing:

    val f = fib()
    println(f(),f(),f(),f())
    
    1 2 3 5 8
    

提交回复
热议问题