什么是具名参数呢?
下面通过简单例子来说明。
需求:有一个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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。