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.

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错