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~~~

以上方法把任意的表达式或者代码块转换为一个函数对象。

posted on 2015-02-12 17:50  白乔  阅读(405)  评论(0编辑  收藏  举报

导航