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