×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala's First Program

By IncludeHelp Last updated : October 07, 2024

Write Scala's first program

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 code to write first program | Print Hello World

So, the basic code to print Hello World in Scala is:

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.

object 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.

main() Method

In the main class (MyClass) there is defined as the main() method. Let's dig in the main() method defined in our code.

def main(args: Array[String]) 

Now, if we see it like any normal method def is keyword used create the method.

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.

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.

The print() Method

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.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.