Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Scala REPL Hello World program

We will see how to create Hello World program in Scala REPL as follows:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).

Type in expressions for evaluation. Or try :help.

scala>"Hello World"

res0: String = Hello World

scala>

Scala is a hybrid language, which means it is object-oriented and functional as well. You can create classes and objects in Scala. Next we will create a complete Hello World application using classes.

Scala object-oriented HelloWorld program

We will see how to create object-oriented HelloWorld program in Scala REPL as follows:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala>object HelloWorld {

| def main(args:Array[String]) = println("Hello World")

| }

defined object HelloWorld scala>HelloWorld.main(null)

Hello World scala>

The first thing you need to realize is that we use the word object instead of class. The Scala language has different constructs compared to Java. Object is a singleton in Scala. It's the same as coding the singleton pattern in Java.

Next we see the word def that is used in Scala to create functions. In the preceding program, we create the main function similar to the way we do it in Java, and we call the built-in function println in order to print the String Hello World. Scala imports some Java objects and packages by default. Coding in Scala does not require you to type, for instance, System.out.println("Hello World"), but you can if you want. Let's take a look at it in the following code:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala>System.out.println("Hello World")

Hello World scala>

We can and we will do better. Scala has some abstractions for a console application, so we can write this code with a lesser number of lines of code. To accomplish this goal, we need to extend the Scala class App. When we extend from App, we perform inheritance and we don't need to define the main function. We can just put all the code in the body of the class, which is very convenient and makes the code clean and simple to read.

 
Source
< Prev   CONTENTS   Source   Next >

Related topics