Trusted answers to developer questions

How to write a hello world program in Scala

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Scala, short for Scalable Language, combines features of object-oriented and functional languages to improve application scalability and reliability.

Scala is based on Java. Hence, the syntax is similar. We can consider a Scala program as a collection of objects that call each others’ methods.

Code

We will begin by writing the conventional Hello world program in the code snippet below:

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

Explanation

  • We first create an object named HelloWorld. An object can hold methods and variables that we can use without first creating an instance of a class. It can also hold static members that are not associated with instances of some other class.

  • Next, we define a method named main.

  • main takes in a single parameter named args of type string array.

  • The unit keyword refers to the return type of the method. Unit is used when a method does not return anything. It is synonymous with void in Java.

  • println is used to output elements on the screen. Anything within " " will appear on the screen.

RELATED TAGS

scala

CONTRIBUTOR

Hassaan Waqar
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?