函数和其他常量、变量一样,也是一个值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
def sum(f:Int=>Int,a:Int,b:Int):Int= if(a>b) 0 else f(a)+sum(f,a+1,b) def f1(a:Int)=a def sum1(a:Int,b:Int):Int=sum(f1,a,b) def f2(a:Int)=a*2 def sum2(a:Int,b:Int):Int=sum(f2,a,b) // function as parameter def sum(f:(Int,Int)=>Int, a:Int, b:Int)=f(a,b) def sum(f:Int=>Int, a:Int, b:Int)=f(a) + b //anonymous function val power = (a:Int) => a^2 //function as return value def sum4(f:Int=Int) = (Int,Int) => Int = { def sum5(a:Int,b:Int):Int=if(a>b) 0 else f(a) + sum5(a+1,b); sum5 } |