How to write Scala main method

 270 total views,  1 views today

Welcome to Scala series. In this tutorial, we will be learning how to write Scala main method.

Before learning to write the main method. Let us understand a few basics.

Scala is a functional oriented language as well as an object oriented language.
To run Scala, you need to have Java installed on your machine.

But why Java?

Because Scala runs on top of JVM. Without JVM there is no Java and hence there is no Scala. Scala works well with Java programs.You can have an application written in Scala alongside Java. This is a major advantage.

What happens behind the scene when you execute a Scala program?

Scala compiler compiles the code and converts your program into byte code.i.e., .class files.

Now Scala interpreter executes this byte code in the Java virtual machine to run your application.

Ok. Let us dive deep into writing the main program.

Scala main method is the entry point for you application.
(or in simple words)
Scala main method is the start of your program

Let us start with our classic “Hello World!!” program.

Hello World using Scala main method.

def main(args: Array[String]): Unit = {
    println("Hello world!!")
}

Description

  1. Method name should be main.
  2. Every Scala method starts with the def keyword.
  3. Method parameter should be a variable of type Array[String]
  4. Followed by curly braces
  5. Since the main method doesn’t return anything, the return here is Unit which means no return.

In Scala, if a method doesn’t return a value, it can be simplified to (no need of Unit keyword.)

def main(args: Array[String]) {
    println("Hello world!!")
}

Scala’s main method is similar to Java’s main method and I believe java programmers can easily understand this structure.

The above main method just prints “Hello world!!” in your console.

How to execute it in Scala interactive shell?

scala> def main(args: Array[String]) {
     |     println("Hello world!!")
     | }
main: (args: Array[String])Unit

scala> main(Array())
Hello world!!

How to wrap it in a class? and run in IDE?

object StaticReference {
  def main(args: Array[String]) {
    println("Hello world!!")
  }
}

Output

Hello world!!

Note: Always the main method can only have a single argument and it should be of type Array.

I hope you have learned to write Scala main method.

References: Official documentation

Thanks for reading. Please leave a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.