什么是具名參數呢?
下面通過簡單例子來說明。
需求:有一個42歲的父親和一個12歲的孩子,求父親比孩子年長多少歲?可以很簡單的寫出下面的函數體來實現,如下圖:

特殊情況來了,如果在使用getDvalue函數時,不小心導致了參數p和c寫顛倒了,那么結果會是下圖所示:

這樣就不是所要的結果了,很小的疏忽導致了結果的不正確性,做一下簡單的修改,如下圖所示:

結果又是我們最開始所需的了。
下面寫幾個錯誤的示例:

code:
package demo
object NamedArgument {
def main(args: Array[String]): Unit = {
val parent=42
val child=12
def getDvalue(p:Int,c:Int):Int={
p-c
}
println("d-value is :"+getDvalue(c=child,p=parent))
def testNA(a:Int,b:String)={}
testNA(1,"string")//right
testNA("string",1)//Multiple markers at this line:
//type mismatch; found : String("string") required: Int
//type mismatch; found : Int(1) required: String
//如果不使用具名參數,調用函數時應按照函數定義的參數順序填寫參數
testNA(b="string",a=1)//right 具名參數
testNA(b="string",1)//positional after named argument.
//如果函數中某個參數沒有具名,則按照其所在位置指定參數,可以叫做位置參數
testNA(b=1,a="string") //Multiple markers at this line:
//type mismatch; found : String("string") required: Int
//type mismatch; found : Int(1) required: String
//type mismatch; found : String("string") required: Int
//具名參數指定類型錯誤,這是比較明顯的錯誤
testNA(1,a="string") //parameter 'a' is already specified at parameter position 1
//參數a已經在位置1(a="string")定義過,與位置參數1(所在位置0)沖突
testNA(1,b="string") //right
testNA(a=1,"string") //right
}
}
接下來試試其它的類型
def testNA2(a:Int*,b:String)={} //*-parameter must come last 這是基本語法的約束,可變參數必須放在最后,這種寫法是錯誤的
def testNA2(a:String,b:Int*)={} //right
testNA2("string",1,2,3,4)//right
testNA2(a="string",b=1,2,3,4)//right
testNA2(1,2,3,4,"string")//type mismatch; found : Int(1) required: String
//type mismatch; found : String("string") required: Int
testNA2(b=1,2,3,4,a="string")
testNA2(b= List(1,2,3,4),a="string")//type mismatch; found : List[Int] required: Int
//這樣會提示類型錯誤,這樣寫其實就不是可變參數了
//可以寫成如下形式testNA3
def testNA3(a:String,b:List[Int])={}
testNA3(b= List(1,2,3,4),a="string")
//匿名參數
def testNA4(a:Int,b:String)=a
val t1: Int=>Int = testNA4(_:Int,"string")
val t2: Int => Int = testNA4(b = "string", a = _) //positional after named argument.
val t3 = testNA4(b = "string", a = _: Int) //positional after named argument.
val t4: Int=>Int = testNA4(_ , b="string") //right
val t5: Int=>Int = testNA4(_ , "string") //right
val t6: Int=>Int = testNA4(a=_ , b="string") //type mismatch; found : Int required: Int=>Int
//匿名參數不能使用具名參數
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。