斯卡拉 |命名参数
在Scala中,当参数通过带有命名参数的函数时,我们可以用参数名称标记参数。这些命名参数与函数的命名参数交叉匹配。在正常情况下,未命名参数使用参数位置进行函数或构造函数调用,但这些命名参数允许我们通过简单地交换顺序来更改传递给函数的参数的顺序。
句法:
Function Definition : def createArray(length:int, capacity:int);
Function calling : createArray(capacity=20, length:10);
防范措施 -
-> If some arguments are named and others are not, the unnamed arguments must come firstfunction(0, b = "1")
-> Order Interchange is validfunction(b = "1", a = 0)
-> Not accepted , error: positional after named argumentfunction(b = "1", 0)
-> Not accepted , parameter ‘a’ specified twice as ‘0’ in first position and again as a = 1function(0, a = 1)
注意:如果 x 参数表达式的形式为x = expr并且 x 不是方法的参数名称,则该参数被视为某个变量 x 的赋值表达式。
例子 :
// Scala program using Named arguments
// Creating object
object GFG
{
// Main method
def main(args: Array[String])
{
// passed with named arguments
printIntiger(X = 6, Y = 8);
}
// Defining a method
def printIntiger( X:Int, Y:Int ) =
{
println("Value of X : " + X );
println("Value of Y : " + Y );
}
}
Value of X : 6
Value of Y : 8
在这里,在上面的示例中,我们创建了 printIntiger函数,然后我们调用了该函数。我们在调用函数时使用函数参数名称。我们传递了参数 X = 6 , Y = 8 这里X和Y是参数的名称。
例子 :
// Scala program using Named arguments
// Creating object
object GFG
{
// Main method
def main(args: Array[String])
{
// without named arguments
printName("geeks","for","geeks");
// passed arguments according to order
printName(first = "Geeks", middle="for",
last = "Geeks");
// passed arguments with different order
printName(last = "Geeks", first = "Geeks",
middle="for");
}
// Defining function
def printName( first: String, middle: String,
last: String ) =
{
println("Ist part of name: " + first )
println("IInd part of name: " + middle )
println("IIIrd part of name: " + last )
}
}
Ist part of name: geeks
IInd part of name: for
IIIrd part of name: geeks
Ist part of name: Geeks
IInd part of name: for
IIIrd part of name: Geeks
Ist part of name: Geeks
IInd part of name: for
IIIrd part of name: Geeks
正如我们在上面的示例中看到的,我们创建了 printName函数,然后我们调用了该函数。在这里,我们在调用函数时使用函数参数名称。通过改变 printName(last = “Geeks”, first = “Geeks”, middle=”for”) 等参数的顺序,我们可以获得相同的结果。