How to return a function in scala

前端 未结 5 1054
忘了有多久
忘了有多久 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条回答
  •  你的背包
    2021-02-02 15:08

    You don't need a temp var when using a tuple:

    def fib() = {
      var t = (1,-1)
      () => { 
        t = (t._1 + t._2, t._1)
        t._1
      }
    }
    

    But in real life you should use Apocalisp's solution.

提交回复
热议问题