scala中“=>”的應用場景
1、表示函數的返回類型
def main(args: Array[String]): Unit = {
//定義一個函數變量
var x: (Int) => Int = test
var x2: (Int) => String = test2
println(x(2)) // 4
println(x2(2)) // 2trx
}
def test(x: Int) = x * 2
def test2(x: Int) = x+"trx"
(Int)=>Int、(Int)=>String 左邊是參數類型,右邊是返回值類型。
2、匿名函數
def main(args: Array[String]): Unit = {
// 定義一個匿名函數
var fun = (x: Int) => x * 2
println(fun(10)) // 20
}
匿名函數定義, 左邊是參數 右邊是函數實現體 (x: Int)=>{}
3、case語句
def main(args: Array[String]): Unit = {
val x = 10
val y = 10
val value = x + y match {
case 20 => x
case 30 => y
}
print(value)
}
在模式匹配 match 和 try-catch 都用 “=>” 表示輸出的結果或返回的值
4、By-Name Parameters(傳名參數)
傳名參數在函數調用前表達式不會被求值,而是會被包裹成一個匿名函數作爲函數參數傳遞下去,例如參數類型爲無參函數的參數就是傳名參數。
object SayHello {
def main(args: Array[String]): Unit = {
println("傳值調用:")
delayed0(time())
println("===================")
println("傳名調用:")
delayed(time())
println("===================")
}
def time() = {
println("獲取時間,單位爲納秒")
System.nanoTime
}
def delayed0(t : Long)={
println("在 delayed0 方法內")
println("參數"+t)
t
}
def delayed(t: => Long) = { //重點在這
println("在 delayed 方法內")
println("參數: " + t)
t
}
}