在 Scala 中执行块 n 次是否有简短的语法? [英] Is there a brief syntax for executing a block n times in Scala?
本文介绍了在 Scala 中执行块 n 次是否有简短的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我想重复执行 n 次时,我发现自己编写了这样的代码:
I find myself writing code like this when I want to repeat some execution n times:
for (i <- 1 to n) { doSomething() }
我正在寻找更短的语法:
I'm looking for a shorter syntax like this:
n.times(doSomething())
Scala 中已经存在这样的东西了吗?
Does something like this exist in Scala already?
编辑
我想过使用 Range 的 foreach() 方法,但是块需要采用一个它从不使用的参数.
I thought about using Range's foreach() method, but then the block needs to take a parameter which it never uses.
(1 to n).foreach(ignored => doSomething())
推荐答案
您可以使用 Pimp My Library 模式轻松定义一个.
You could easily define one using Pimp My Library pattern.
scala> implicit def intWithTimes(n: Int) = new {
| def times(f: => Unit) = 1 to n foreach {_ => f}
| }
intWithTimes: (n: Int)java.lang.Object{def times(f: => Unit): Unit}
scala> 5 times {
| println("Hello World")
| }
Hello World
Hello World
Hello World
Hello World
Hello World
这篇关于在 Scala 中执行块 n 次是否有简短的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文