scala学习笔记:无参函数

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学习笔记:无参函数)