Scala中的基本程序 (Basic program in Scala)
As your first Scala program, we will see a basic output program that just prints "Hello World" or any other similar type of string. With this example, we will see what are the part of the code that is important and why they are used?
作為您的第一個Scala程序 ,我們將看到一個基本的輸出程序,該程序僅打印“ Hello World”或任何其他類似類型的字符串。 在此示例中,我們將看到重要的代碼部分以及為什么使用它們?
So, the basic code to print Hello World in Scala is:
因此, 在Scala中打印Hello World的基本代碼是:
object MyClass {
def main(args: Array[String]) {
print("Hello World!");
}
}
Output
輸出量
Hello World!
In this code, if you have observed there are three parts, the class definition, main() function and the print statement. We will discuss each of them in detail.
在這段代碼中,如果您觀察到了三部分,則是類定義, main()函數和print語句。 我們將詳細討論它們中的每一個。
object MyClass
對象MyClass
If you are familiar with object-oriented programming (especially java) you would know that every method needs a class for execution. So this is the main class defined in Scala. The main class is simply a class that contains the main() function. Here, we have named our main class MyClass. Now we will define a method named main in this class which will start execution when the code will run.
如果您熟悉面向對象的編程(尤其是Java),則將知道每個方法都需要一個用于執行的類。 因此,這是Scala中定義的主要類 。 主類只是包含main()函數的類 。 在這里,我們將主類命名為MyClass 。 現在,我們將在此類中定義一個名為main的方法,該方法將在代碼運行時開始執行。
main() method
main()方法
In the main class (MyClass) there is defined as the main() method. Let's dig in the main() method defined in our code.
在主類( MyClass )中,將其定義為main()方法 。 讓我們深入研究代碼中定義的main()方法。
def main(args: Array[String])
Now, if we see it like any normal method def is keyword used create the method.
現在,如果我們看到它像使用任何常規方法def是關鍵字一樣,請創建該方法。
Next is the name of the method, in our case it is main() this tells the compiler that this method needs to be called first when the code is running.
接下來是方法的名稱,在我們的例子中是main(),它告訴編譯器在代碼運行時需要首先調用此方法。
Then comes the set of parameters that are being passed to the method. Here, since the call is from the starting point i.e. there is no caller that can pass value it. Therefore, the parameters it takes can we 0, its variable parameters of a function. The parameters are passed in the function are called command-line arguments. These are passed as a string variable to the function. Then the main code that will run on the execution of the code is written in the main function.
然后是傳遞給該方法的參數集。 在這里,由于調用是從起點開始的,即沒有調用者可以傳遞值。 因此,它需要的參數可以為0, 即函數的可變參數 。 在函數中傳遞的參數稱為命令行參數。 這些作為字符串變量傳遞給函數。 然后,將在執行代碼時運行的主要代碼寫入main函數中。
print() Method
print()方法
In the main() function here we have only one line of code that has a print method. The print() method take a string value as input and prints it on screen. You can add variables using the "+" sign that we will see in the next article.
在main()函數中 ,只有一行代碼具有打印方法。 print()方法將字符串值作為輸入并將其打印在屏幕上。 您可以使用在下一篇文章中看到的“ +”號添加變量。
翻譯自: https://www.includehelp.com/scala/basic-program-print-hello-world-in-scala.aspx