scala中命名參數函數
具有命名參數的函數 (Functions with named arguments )
A function is Scala can take multiple arguments. These arguments are traditionally called in sequence while calling a function. But in Scala programming, the program is given the power to alter the traditional sequence of arguments. Scala provides its users named arguments these are used to change the order of using arguments at call.
一個函數是Scala可以接受多個參數。 這些參數通常在調用函數時按順序調用。 但是在Scala編程中,程序有權更改傳統的參數順序。 Scala為用戶提供了命名參數,這些參數用于更改調用時使用參數的順序。
Suppose a function that has two variables var1 and var2. If we want to initialize var2 first then the following syntax is used.
假設一個函數具有兩個變量var1和var2 。 如果我們要首先初始化var2,則使用以下語法。
Syntax:
句法:
functionName ( var2 = value2, var2 = value1 );
Explanation:
說明:
This will pass the value2 to the second argument in the list. And value1 in the first argument in the list.
這會將value2傳遞給列表中的第二個參數。 并在列表中的第一個參數中使用value1。
Example:
例:
object Demo {
def sub( a:Int, b:Int ) = {
println("Substraction = " + (a-b) );
}
def main(args: Array[String]) {
println("The fucntion is called using named function call")
sub(b = 5, a = 7);
}
}
Output
輸出量
The fucntion is called using named function call
Substraction = 2
Explanation:
說明:
This code displays how to use named arguments in Scala? The code initializes a function named sub(), it expects two arguments and substracts second from first. At function call, the arguments are filled using the names that initialize them in the order the programmer wants.
此代碼顯示如何在Scala中使用命名參數? 該代碼初始化了一個名為sub()的函數,它需要兩個參數并從第一個減去第二個。 在函數調用時,將使用按程序員想要的順序對其進行初始化的名稱來填充參數。
翻譯自: https://www.includehelp.com/scala/functions-with-named-arguments-in-scala.aspx
scala中命名參數函數