您好,登錄后才能下訂單哦!
什么是具名參數(shù)呢?
下面通過簡(jiǎn)單例子來說明。
需求:有一個(gè)42歲的父親和一個(gè)12歲的孩子,求父親比孩子年長(zhǎng)多少歲?可以很簡(jiǎn)單的寫出下面的函數(shù)體來實(shí)現(xiàn),如下圖:
特殊情況來了,如果在使用getDvalue函數(shù)時(shí),不小心導(dǎo)致了參數(shù)p和c寫顛倒了,那么結(jié)果會(huì)是下圖所示:
這樣就不是所要的結(jié)果了,很小的疏忽導(dǎo)致了結(jié)果的不正確性,做一下簡(jiǎn)單的修改,如下圖所示:
結(jié)果又是我們最開始所需的了。
下面寫幾個(gè)錯(cuò)誤的示例:
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
//如果不使用具名參數(shù),調(diào)用函數(shù)時(shí)應(yīng)按照函數(shù)定義的參數(shù)順序填寫參數(shù)
testNA(b="string",a=1)//right 具名參數(shù)
testNA(b="string",1)//positional after named argument.
//如果函數(shù)中某個(gè)參數(shù)沒有具名,則按照其所在位置指定參數(shù),可以叫做位置參數(shù)
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
//具名參數(shù)指定類型錯(cuò)誤,這是比較明顯的錯(cuò)誤
testNA(1,a="string") //parameter 'a' is already specified at parameter position 1
//參數(shù)a已經(jīng)在位置1(a="string")定義過,與位置參數(shù)1(所在位置0)沖突
testNA(1,b="string") //right
testNA(a=1,"string") //right
}
}
接下來試試其它的類型
def testNA2(a:Int*,b:String)={} //*-parameter must come last 這是基本語法的約束,可變參數(shù)必須放在最后,這種寫法是錯(cuò)誤的
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
//這樣會(huì)提示類型錯(cuò)誤,這樣寫其實(shí)就不是可變參數(shù)了
//可以寫成如下形式testNA3
def testNA3(a:String,b:List[Int])={}
testNA3(b= List(1,2,3,4),a="string")
//匿名參數(shù)
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
//匿名參數(shù)不能使用具名參數(shù)
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。