方法参数
一、普通参数
1 2 3 4 5
| def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum }
|
二、传值调用和传名调用: =>
两者的区别主要在于变量名和变量类型之间是否多了一个 =>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| object Test { def main(args: Array[String]) { delayed(time()); delayed2(time()); }
def time() = { println("获取时间,单位为纳秒") System.nanoTime } def delayed2( t: => Long ) = { println("在 delayed 方法内") println("参数: " + t) t } def delayed( t: Long ) = { println("在 delayed 方法内") println("参数: " + t) t } }
|
三、参数顺序
通过在调用者端添加
参数名=
1 2 3 4 5 6 7 8 9
| object Test { def main(args: Array[String]) { printInt(b=5, a=7); } def printInt( a:Int, b:Int ) = { println("Value of a : " + a ); println("Value of b : " + b ); } }
|
四、可变参数
感觉就是一个数组
1 2 3 4 5 6 7 8 9 10 11 12
| object Test { def main(args: Array[String]) { printStrings("Runoob", "Scala", "Python"); } def printStrings( args:String* ) = { var i : Int = 0; for( arg <- args ){ println("Arg value[" + i + "] = " + arg ); i = i + 1; } } }
|
五、默认参数
1 2 3 4 5 6 7 8 9 10
| object Test { def main(args: Array[String]) { println( "返回值 : " + addInt() ); } def addInt( a:Int=5, b:Int=7 ) : Int = { var sum:Int = 0 sum = a + b return sum } }
|
六、高阶函数
1 2 3 4 5 6 7 8 9 10
| object Test { def main(args: Array[String]) {7 println( apply( layout, 10) ) } def apply(f: => String, v: Int) = f(v) def layout[A](x: A) = "[" + x.toString() + "]" }
|
七、匿名函数
1 2 3 4 5
| var inc = (x:Int) => x+1 print(inc(2))
var userDir = () => { System.getProperty("user.dir") } println( userDir() )
|
八、偏函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import java.util.Date
object Test { def main(args: Array[String]) { val date = new Date val logWithDateBound = log(date, _ : String)
logWithDateBound("message1" ) Thread.sleep(1000) logWithDateBound("message2" ) Thread.sleep(1000) logWithDateBound("message3" ) }
def log(date: Date, message: String) = { println(date + "----" + message) } }
|