Scala Syntax: An Introductory Scala Tutorial

Free Scala course with real-time projects Start Now!!

This article aims to explain to you the basic Scala Syntax. Though it is a bit different from Java Syntax or C++, we’ll get used to it. Along with this, we will learn Scala Keywords, Scala Identifiers, Scala Packages, and Scala Comments.

So, let’s begin the Scala Syntax Tutorial.

Introduction to Scala Syntax

We can look at a Scala program as a collection of objects that invoke each other’s methods to communicate. One major difference between Scala and Java is that here, in Scala, we don’t need to end each statement with a semicolon(;).

Basic Scala Constructs

Let’s start with the basic structures- expressions, blocks, classes, objects, functions, methods, traits, Main method, fields, and closures.

a. Scala Expression

An expression is a computable statement. For example, the following is an expression:
1+2
We use println() to print the output of an expression:

println(1) //1
println(1+2) //3
println(“Hi”) //Hi
println(“Hi”+” User”) //Hi User
  1. Values

An expression returns a result; we can name it using the ‘val’ keyword.

val name=’Ayushi’
println(name)

Such an entity has only one value; we cannot reassign it. Also, when we reference it again, that does not recompute its value.

val name=”Ayushi”
name=”Megha” //This doesn’t compile

Usually, Scala will infer the type of an expression- type inference, as we’ve discussed in Features of Scala. But we can also explicitly state the type:

val roll:Int = 30
  1. Scala Variables

A variable is a value that we can reassign. To declare a variable, we use the ‘var’ keyword. Scala Syntax for Variables are given below.

var x=2
x=3 //This changes the value of x from 2 to 3
println(x*x) //This prints 9

We can declare the type of the variable:

var roll:Int = 30

b. Scala Block

A block is a group of expressions delimited by curly braces({}). A block returns whatever its last expression returns. The Scala Syntax for the Same is Below.

println
(
{
val x=1+1
x+1
}
) //3

c. Scala Class

Scala class is a blueprint that we can use to create an object. It may hold values, variables, types, classes, functions, methods, objects, and traits. We collectively call them members. To declare a class, we use the keyword ‘class’ and an identifier.

object Main extends App

 {
    class Fruit{}
    val orange=new Fruit
}

Here, to create an instance of this, we use the keyword ‘new’. An instance of a class can have behaviors and states. For example, a car has states- brand, model, color, and behaviors- start, turn, stop. Here, orange is an instance of class Fruit.

We’ll see more on classes and objects in a later tutorial.

d. Scala Object

It is a single instance of its own definition(a singleton of its own class). To define an object, we use the keyword ‘object’.

object Main extends App {
    object MyObject{
        def plusthree()={
        val x=3*3
        x+3}
    }
    println(MyObject.plusthree) //This prints 12
}

We’ll cover this in a later tutorial.

e. Scala Function

A function is an expression that takes parameters. First, let’s observe an anonymous function.

(x:Int)=>x*x

This function takes an Integer argument x, and returns its square.

So, here we see that on the left of => is the list of parameters, and on the right is an expression it will return. Now, let’s give it a name.

val squared=(x:Int)=>x*x

To get the output, we call the function:

println(squared(3)) //This prints 9

A function may also take multiple parameters or none.

val add=(x:Int,y:Int,z:Int)=>x+y+z
println(add(2,3,7)) //This prints 12
val sayhi=()=>(println(“Hi”)) //We could also have put the println in a block as {print(“Hi”)}
sayhi() //This prints Hi

f. Scala Method

A method is similar to a function, but we define it using the keyword ‘def’. What follows is an identifier, parameter lists, a return type, and a body. Let’s take an example.

def squared(x:Int):Int=x*x
println(squared(3)) //This prints 9

We denote the return type after a colon after the parameter list. Also, here, we use = instead of =>.
A method can also take multiple parameter lists.

def mymethod(x:Int,y:Int)(z:Int):Int={(x+y)*z}
println(mymethod(2,3)(4)) //This prints 20 from ((2+3)*4)
Now, let’s try something with no parameter lists.
def method1():String="Hello"
println(method1) //This would work too:    println(method1())

A method can have multiline expressions:

def method2(x:Int,y:Int)(z:Int):Int={
    val a=z+y+x
    (x+y)*a
}
println(method2(2,3)(4))

The last expression is the return value. Scala does have a ‘return’ keyword, but we’ll see that later.

g. Scala Trait

A trait holds fields and methods, and we define it using the ‘trait’ keyword. We can also combine traits.

trait greeter
{
    def greet(name:String):Unit
}

We’ll see this in detail later.

h. Scala Main Method

The main method is an entry point for the program. JVM needs a method with an argument which is an array of strings.

object Main
{
def main(args: Array[String]): Unit =
println("Hello, Scala developer!")
}

i. Fields

A unique set of instance variables belongs to each object. These are fields, and they define the object’s state.

j. Closure

Any function whose return value depends on variables declared outside it.
Any Doubt yet in Scala Syntax? Please Comment.

An Example of Scala Program

Let’s try the first “Hello, World!” program in Scala. Like many other languages, we may execute a Scala program in one of two modes- interactive mode and script mode.

a. Interactive Mode

Open the Command Prompt on Windows using ‘cmd’ in Run. Then, type ‘scala’.

Microsoft Windows [Version 10.0.16299.309]

(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\lifei>scala

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

Type in expressions for evaluation. Or try :help.

scala>

Now, you can execute any statement here.

b. Script Mode

To execute a program in script mode, type your program in the Notepad.
object hello extends App

{
    println("Hello")
}

Now, get back to the command prompt, and get to the location where your file is.

C:\Users\lifei>cd Desktop

C:\Users\lifei\Desktop>

Then, to compile your program, type the following:

C:\Users\lifei\Desktop>scalac hw.scala

This creates some class files in the current directory. One of these is hello.class. This is the

bytecode, and finally, to run this bytecode, use the command scala:

C:\Users\lifei\Desktop>scala hello

Hello

Scala Syntax Rules

There are some basic syntax rules we must take care of while coding with Scala. Let’s discuss those.

a. Case-Sensitive

Scala is case-sensitive. This means that it treats the identifiers ‘hello’ and ‘Hello’ differently.

b. Class Names

You should name a class in Pascal case. This means that instead of naming it like ‘hihelloworld’, you will name it ‘HiHelloWorld’.

c. Method Names

A method’s name should be in Camel case. So, the correct way would be something like ‘sayHelloToTheWorld()’.

Scala Keywords

Scala reserves some words so it can function. These are:

Abstract    case        catch        class

def        do        else        extends

false        final        finally        for

forSome    if        implicit        import

lazy        match        new        Null

object        override    package    private

protected    return        sealed        super

this        throw        trait        Try

true        type        val        Var

while        with        yield        –

:        =        =>        <-

<:        <%        >:        #

@

We can’t use any of these words as identifiers or constants.

Scala Identifiers

What names can we use for entities like objects, classes, methods, and variables? We call them identifiers, and there are some rules to what names we can use for this purpose:

  1. It cannot be a reserved keyword.
  2. It is case-sensitive.

Scala supports four kinds of identifiers:

a. Alphanumeric Identifiers in Scala

These begin with a letter(A-Z/a-z) or an underscore. This can be followed by letters, digits, or underscores. You cannot use ‘$’, since it is a keyword.

Legally valid examples: age, _8bit, __magic__

Legally invalid examples: $99, 9lives, -23.47

b. Operator Identifiers in Scala

These may have one or more operator characters. So, what are operator characters? Printable ASCII characters like +, :, ?, ~, or #.

Legally valid examples:

+

++

:::

<?>

:>

The compiler internally mangles these to turn them into legal Java identifiers with embedded $ characters. For example, it would represent :-> as $colon$minus$greater.

c. Mixed Identifiers in Scala

These contain an alphanumeric identifier followed by an underscore and an operator identifier.

Legally valid examples:

unary_+

mine_=

d. Literal Identifiers in Scala

Such an identifier is an arbitrary string delimited by back ticks(`…..`).

Legally valid examples:

`x`

`yield`

`hello`

Scala Comments

Just like Java, Scala supports single-line and multiline comments.

// This is a single-line comment

/* This is the first line of a multiline comment

This is the middle

And this is the last*/

The compiler ignores comments. Read up on Comments in Scala for a detailed explanation on comments.

Blank Lines and Whitespace

A line that contains only whitespace, and possibly comments, is a blank line, and Scala just ignores it. Also, we can separate tokens by whitespace characters and/or comments.

Newline Characters

Scala is line-oriented; we may terminate statements with semicolons(;) or with newlines. This means that semicolons are optional to end a statement. If only a single statement appears on a line, we don’t have to use it necessarily. But if we must fit multiple statements into one line, we must separate them with semicolons:

val x=7; println(x)

Scala Packages

A module of code is a package with a name. For example, take a look at the Lift utility package

net.liftweb.util. In the source file, the package declaration is the first non-comment line:

package com.liftcode.stuff

To refer a package in the current compilation scope, we can import a package:

import scala.xml._

We can also import a single class and object from a package:

import scala.collection.mutable.HashMap

And to import more than one class or object:

import scala.collection.immutable.{TreeMap, TreeSet}

This was all about the Scala Syntax.

Conclusion

We can guarantee you’ll be able to write basic Scala code now. Tell us how it works for you. Also leave your doubts and comments regarding the Scala Syntax in the comment section.

Reference

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

2 Responses

  1. Yaw Kusi says:

    Great job!

  2. Gowtham says:

    Nice content

Leave a Reply

Your email address will not be published. Required fields are marked *