scala学习笔记:控制抽象

def repeat(n:Int)(action: =>Unit)=for(i<-1 to n)action

var i = 0
repeat(5){ println(i=i+1) }

另外一个例子:

scala> def until(condition: =>Boolean)(action: =>Unit) {
     | if(!condition){
     | action
     | until(condition)(action)
     | }
     | }
until: (condition: => Boolean)(action: => Unit)Unit

scala> var i = 0
i: Int = 0

scala> until(i>5){i=i+1;println(i)}
1
2
3
4
5
6

scala> def incAndPrint={i=i+1;println(i)}
incAndPrint: Unit

scala> until(i>10)(incAndPrint)
7
8
9
10
11

再来写一个:

def foreach(list:Iterable[Any])(action:(Any) => Unit){ val it = list.iterator while(it.hasNext){ action(it.next()) } } foreach(1 to 5){println(_)}

你可能感兴趣的:(scala学习笔记:控制抽象)