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 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?