scala> def repeat(times:Int)(run:()=>Unit)=for(i<-1 to times)run()
repeat: (times: Int)(run: () => Unit)Unit
scala> repeat(2){println("haha~~~")}
<console>:9: error: type mismatch;
found : Unit
required: () => Unit
repeat(2){println("haha~~~")}
^
scala> repeat(2){()=>println("haha~~~")}
haha~~~
haha~~~
为了去掉()=>这样的写法,将run()方法声明为没有参数的函数:
scala> def repeat(times:Int)(run: =>Unit)=for(i<-1 to times)run
repeat: (times: Int)(run: => Unit)Unit
scala> repeat(2){println("haha~~~")}
haha~~~
haha~~~
以上方法把任意的表达式或者代码块转换为一个函数对象。
本文介绍了一种在Scala中定义可以重复执行特定次数代码块的方法。通过定义一个名为repeat的函数,该函数接受一个整数参数times和一个无参的Unit返回类型的函数run。使用这种方式可以在不直接指定函数的情况下重复执行代码块。
1738

被折叠的 条评论
为什么被折叠?



