duanlvji4780
2013-09-17 08:45
浏览 78

Scala是否具有等同于golangs defer的功能?

Does Scala have an equivelent to golangs defer?

from: http://golang.org/doc/effective_go.html#defer

Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return. The canonical examples are unlocking a mutex or closing a file.

图片转代码服务由CSDN问答提供 功能建议

Scala是否具有等同于golangs延期的条件?

来自: http://golang.org/doc/effective_go.html#defer

Go的defer语句安排一个函数调用(延迟的函数)在执行延迟的函数返回之前立即运行。 这是一种不寻常但有效的处理情况的方法,例如无论函数返回哪个路径都必须释放资源。 典型的例子是解锁互斥锁或关闭文件。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douwen2158 2013-09-17 21:22
    已采纳

    Scala does not offer defer by design, however you can create it yourself by wrapping your function in another function, passing an object which keeps track of functions to call.

    Example:

    class DeferTracker() {
      class LazyVal[A](val value:() => A)
    
      private var l = List[LazyVal[Any]]()
      def apply(f: => Any) = { l = new LazyVal(() => f) :: l }
      def makeCalls() = l.foreach { x => x.value() }
    }
    
    def Deferrable[A](context: DeferTracker => A) = {
      val dt = new DeferTracker()
      val res = context(dt)
      dt.makeCalls
      res
    }
    

    In this example, Deferable would be the wrapping function which calls context and returns it contents, giving it an object which tracks defer calls.

    You can use this construct like this:

    def dtest(x:Int) = println("dtest: " + x)
    
    def someFunction(x:Int):Int = Deferrable { defer =>
      defer(dtest(x))
      println("before return")
      defer(dtest(2*x))
    
      x * 3
    }
    
    println(someFunction(3))
    

    The output would be:

    before return
    dtest: 6
    dtest: 3
    3
    

    I'm aware that this can be solved differently but it is really just an example that Scala supports the concept of defer without too much fuss.

    评论
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题