What's the Scala way to implement a retry-able call like this one?

前端 未结 14 1706
甜味超标
甜味超标 2020-11-29 16:08

Still the newbie in Scala and I\'m now looking for a way to implement the following code on it:

@Override
public void store(InputStream source, String destin         


        
14条回答
  •  借酒劲吻你
    2020-11-29 16:52

    I'd suggest this -

    def retry[T](n: Int)(code: => T) : T = { 
      var res : Option[T] = None
      var left = n 
      while(!res.isDefined) {
        left = left - 1 
        try { 
          res = Some(code) 
        } catch { 
          case t: Throwable if left > 0 => 
        }
      } 
      res.get
    } 
    

    It does:

    scala> retry(3) { println("foo"); }
    foo
    
    scala> retry(4) { throw new RuntimeException("nope"); }
    java.lang.RuntimeException: nope
            at $anonfun$1.apply(:7)
            at $anonfun$1.apply(:7)
            at .retry(:11)
            at .(:7)
            at .()
            at RequestResult$.(:9)
            at RequestResult$.()
            at RequestResult$scala_repl_result()
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$17.apply(Interpreter.scala:988)
            at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$17.apply(Interpreter....
    scala> var i = 0 ;
    i: Int = 0
    
    scala> retry(3) { i = i + 1; if(i < 3) throw new RuntimeException("meh");}
    
    scala> i
    res3: Int = 3
    

    It can probably be improved to be more idiomatic Scala, but I am not a big fan of one-liners that require the reader to know the entire standard library by heart anyways.

提交回复
热议问题