Most elegant repeat loop in Scala

前端 未结 4 891
遇见更好的自我
遇见更好的自我 2021-02-01 01:56

I\'m looking for an equivalent of:

for(_ <- 1 to n)
  some.code()

that would be shortest and most elegant. Isn\'t there in Scala anything si

4条回答
  •  一个人的身影
    2021-02-01 02:40

    You can create a helper method

    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n-1)(f) } }
    

    and use it:

    rep(5) { println("hi") }
    

    Based on @Jörgs comment I have written such a times-method:

    class Rep(n: Int) {
      def times[A](f: => A) { loop(f, n) }
      private def loop[A](f: => A, n: Int) { if (n > 0) { f; loop(f, n-1) } }
    }
    implicit def int2Rep(i: Int): Rep = new Rep(i)
    
    // use it with
    10.times { println("hi") }
    

    Based on @DanGordon comments, I have written such a times-method:

    implicit class Rep(n: Int) {
        def times[A](f: => A) { 1 to n foreach(_ => f) } 
    }
    
    // use it with
    10.times { println("hi") }
    

提交回复
热议问题