What are Scala continuations and why use them?

前端 未结 7 1328
梦谈多话
梦谈多话 2020-11-30 16:58

I just finished Programming in Scala, and I\'ve been looking into the changes between Scala 2.7 and 2.8. The one that seems to be the most important is the continua

7条回答
  •  广开言路
    2020-11-30 17:24

    Continuation capture the state of a computation, to be invoked later.

    Think of the computation between leaving the shift expression and leaving the reset expression as a function. Inside the shift expression this function is called k, it is the continuation. You can pass it around, invoke it later, even more than once.

    I think the value returned by the reset expression is the value of the expression inside the shift expression after the =>, but about this I'm not quite sure.

    So with continuations you can wrap up a rather arbitrary and non-local piece of code in a function. This can be used to implement non-standard control flow, such as coroutining or backtracking.

    So continuations should be used on a system level. Sprinkling them through your application code would be a sure recipe for nightmares, much worse than the worst spaghetti code using goto could ever be.

    Disclaimer: I have no in depth understanding of continuations in Scala, I just inferred it from looking at the examples and knowing continuations from Scheme.

提交回复
热议问题