scala語言示例
Scala var關鍵字 (Scala var keyword)
The var Keyword in scala is used to declare variables. As Scala does not require explicit declaration of data type of the variable, var keyword is used. The variable declared using the var keyword as mutable variables.
scala中的var關鍵字用于聲明變量。 由于Scala不需要顯式聲明變量的數據類型,因此使用var關鍵字 。 使用var關鍵字聲明的變量為可變變量。
Mutable Variables are those variable whose value can be changed in the program, these are used when you need variables which are updated as per the logic of the program. Example of some mutable variables are counters, loop variables, sum, etc.
可變變量是可以在程序中更改其值的那些變量,當您需要根據程序邏輯進行更新的變量時,將使用這些變量。 某些可變變量的示例包括計數器,循環變量,總和等。
Syntax to define mutable variables in Scala using var keyword:
使用var關鍵字在Scala中定義可變變量的語法:
var I = 102;
var H : string = "IncludeHelp";
Syntax explanation, in the first on we have declared a variable I using var keyword. This can be changed in future. The value is 102 so scala will itself make it an int type. In the second one we have explicitly declared the data type of the variable. This is a good practice and you know the limitation of the initialization. It declares the var H as a string using variable. The value will be strictly string and if we stored a number in it will be stored as a string.
語法說明,首先,我們使用var keyword聲明了變量I。 將來可以更改。 值是102,因此scala本身會將其設置為int類型。 在第二篇文章中,我們明確聲明了變量的數據類型。 這是一個好習慣,您知道初始化的局限性。 它使用變量將var H聲明為字符串。 該值將嚴格為字符串,如果我們在其中存儲了數字,則將其存儲為字符串。
Using var keyword you can define variables of all data types in Scala. The value of variables declared using the var keyword can be changed at any point in the program.
使用var關鍵字,您可以在Scala中定義所有數據類型的變量。 使用var關鍵字聲明的變量的值可以在程序的任何位置更改。
Scala程序演示var關鍵字示例 (Scala program to demonstrate example of var keyword)
// Program that displays usage of var keyword in Scala
object VarKeyword {
def main(args: Array[String]) {
var myVar = 52;//Variable Initialized with value 52
print("Value of my myVar =" + myVar + "\n")
myVar = myVar + 6; // Value changes to 52+6
print("Changed Value of myVar = " + myVar )
}
}
Output
輸出量
Value of my myVar =52
Changed Value of myVar = 58
Example explanation:
示例說明:
The code displays use of var keyword in real world program. The variable myVar's value changes in the program.
該代碼顯示了在實際程序中var關鍵字的使用。 變量myVar的值在程序中更改。
翻譯自: https://www.includehelp.com/scala/var-keyword-with-example-in-scala.aspx
scala語言示例