[Groovy] 在Groovy中優雅的實現do while


Groovy原生是不支持do while的,參考

曲線救國,可以這么用

class Looper {
   private Closure code

   static Looper loop( Closure code ) {
      new Looper(code:code)
   }

   void until( Closure test ) {
      code()
      while (!test()) {
         code()
      }
   }
}
import static Looper.*

int i = 0
loop {
   println("Looping : "  + i)
   i += 1
} until { i == 5 }

注意 until 這里用的是大括號,才能讓條件變成一個閉包

實際使用場景,我們接口中需要調用外部接口,外部接口不是很穩定,容易出錯,所以加入了出錯重試機制,一共重試三次,三次過后還是不行才放棄。

def responseString = null
        Exception exception = null
        //出錯重試
        int retry = 0

        Looper.loop {
            try{
                responseString = HttpUtil.post(url, JSONObject.toJSONString(post), header, 10000, 10000)
            }catch (Exception ex){
                exception = ex
            }finally{
                retry++
            }
        }until { exception == null || retry == 3 }


        if(exception != null){
            throw exception
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM