scala中def
Scala def關鍵字 (Scala def keyword)
The def keyword in Scala is used to declare functions and methods in Scala. Scala being ignorant on the data types does the same with the return type of a function. Declaring and defining a function in Scala does not strictly require a return type. The def keyword usage makes the Scala program more flexible.
Scala中的def關鍵字用于在Scala中聲明函數和方法。 對數據類型無知的Scala與函數的返回類型相同。 在Scala中聲明和定義函數并不嚴格要求返回類型。 def關鍵字的使用使Scala程序更加靈活。
The function or methods that are defined using Scala def keyword get evaluated when they are called. This practice reduces the load on compiler because if a function is not called in some case. It is not evaluated.
使用Scala def關鍵字定義的函數或方法在被調用時會得到評估。 這種做法減少了編譯器的負擔,因為如果在某些情況下未調用函數。 不評估。
A function is said to be an anonymous function ( without a name ) if it is declared without using the def keyword and cannot be referenced. So, the functions with def keyword are used when the function call is required. And giving a name to it is important and using def keyword allows it.
如果某個函數未使用def關鍵字進行聲明且無法引用,則稱該函數為匿名函數(無名稱)。 因此,當需要調用函數時,將使用帶有def關鍵字的函數。 給它起一個名字很重要,并且使用def關鍵字允許它。
Syntax (declaration):
語法(聲明):
def function_name(arguments ) : returntype;
Definition:
定義:
def function_name(arguments) : returntype {
//code to be executed...
}
Syntax explanation:
語法說明:
Here, Scala def keyword is used to define the function, the set of arguments of the function are enclosed in the brackets and an optional return type can also be given.
在這里,使用Scala def關鍵字定義函數,函數的參數集放在方括號中,還可以提供可選的返回類型。
Example code:
示例代碼:
object MyClass {
def add(x:Int, y:Int) : Int = {
var sum = x+y ;
return sum;
}
def main(args: Array[String]) {
print("sum of x + y = " + add(25,10));
}
}
Output
輸出量
sum of x + y = 35
Code explanation:
代碼說明:
The above code prints the sum of two numbers using a function. The function add is used to add two numbers and returns their result. The function used Int return type to return the sum of two numbers passes as arguments of the function. The returned value is printed using the print function in the main class.
上面的代碼使用一個函數打印兩個數字的和。 函數add用于將兩個數字相加并返回其結果。 該函數使用Int返回類型返回兩個數字的和,作為函數的參數傳遞。 返回的值使用主類中的打印功能進行打印。
翻譯自: https://www.includehelp.com/scala/def-keyword-with-example-in-scala.aspx
scala中def