Scala Quick Basics

This post will help you in learning the very basics of scala in a very short time. This post doesn’t aim to cover every aspects of scala , the aim is to quickly introduce you to scala and its very basics.

Quick Definition: Scala is Object Oriented, functional in a sense every function is a value, has powerful pattern matching capabilities, runs on JRE. There are lots of other aspects to scala which we will cover in future posts.

Vals and Variables

val x = 10;

scala ‘val ‘is immutable. Hence you cannot put x = 3. This will throw error : reassignment to val. To print the value of x, println statements is available. println(x);

Main Method

A method with name main is the entry point to a scala program. The java virtual machine needs a method with name main that takes an array of strings.

object App {
  def main(args: Array[String]): Unit =
    println("StackRules!");
}

We will cover objects later in this post. The above code defines an object with name App and it contains only one method main, acting as the entry point of execution.

Type Inference

Scala is can infer the type of the val or var by the value assigned. For example, in the above example val x = 10; scala reads this as val x: Int = 10;

The type scala can infer but if you want you can specify the type as

val x: Type = value;

Variables or var in scala indicates, these are mutables and their values can be changed. It is a good practice to stick with val and use var only as a rare case or for special needs.

var x = 10;

x = 20;

This is correct as you can change a var

Functions and Methods

In scala, functions are expressions that has parameters and takes arguments. This is very easy to understand with examples.

val multiplyByTwo = (x:Int) => x*2;
 multiplyByTwo(20);

Here we defined a function that takes a single argument and multiplies it by two. This function is assigned to the val multiplyByTwo. If you omit the assignment to val, then it becomes an anonymous function, a function with no name !

Let us look at some more examples of functions

// A function with two arguments
(x:Int, y: Int) => x+y;

val a = () => 10;
// a function with no arguments

Methods

Methods in scala are defined using the def keyword. The structure of a method is as below

def name ( parameter1, parameter2, parameter x) : return type => body

def sum(x: Int, y: Int): Int = x + y;
val result = sum(10,20);
println(result);

Another interesting thing in scala is , a method can take multiple parameter lists. So instead of passing say 3 parameters to a function as in ( param1, param2, param3) we can instead pass it as (param1, param2) ( param3). Take a look at the example to understand this

//Two parameter lists, first list with two parameters and the other with single parameter
def sum(x: Int, y: Int)(z:Int): Int = x + y + z ;
//Invoking the function
sum(10,20)(30); 

If the method has multiple lines, they need to be enclosed in blocks using { }

//block { } for writing multiple lines
def sum(x: Int, y: Int)(z:Int): Int= { 
  x + y+ z;
};

Classes

In scala, classes are declared using the class keyword followed by it’s name and constructor parameters.

class Order(orderId: String, customerId: String) {
  def PrintOrderId(): Unit = println(orderId)
}

This class , “Order “takes two constructor arguments denoting orderId and customerId.
It has a single method PrintOrderId that just prints the orderId to console.
The method doesn’t have anything to return back to the caller, such methods in other languages like Java, use keyword void to indicate the same. Scala, uses Unit instead of void. Unit is also a type in scala that doesn’t contain anything. So you can assign a Unit to val and print its value.

An instance of class is created using the new keyword

val order = new Order("100","C1");
order.PrintOrderId();
//class with no constructor arguments
class Test {
   def SayHello():String = "Hello";
}

Scala has a special class type called case class and it is one of the most powerful features that makes it more powerful and developer friendly.

Case Classes

Case classes are immutable where as a normal class is not immutable. You can define case classes with the case class keyword: You can instantiate a case class without the new keyword.

case class name ( args)

//Define a case class
case class Color(red: Int, blue: Int, green:Int);
val color1 = Color(100,100,255);
val color2 = Color(100,100,255);

Keep in mind, normal classes are compared using their references, where as case classes are compared using its value. When issue , println(color1==color2); The output will be true. Even though we can two vals and two case class instances, they are same as they contain the same value. For a normal class, this will return false as they are compared using references.

Object

In scala, a singleton is a class that can have only one instance. Such an instance is created using the object keyword in scala. When you want a class or a type to have only one instance, you define it as an object and not as a class. Since you can’t create an Object but you refer it using its name.

object Score {
var cnt:Int = 0
def getNext(): Int = {
cnt = cnt+1;
cnt;
}
}

Accessing the object

An object is accessed using its name.

val result = Score.getNext();
 println(result);

There is also another important aspect in scala called traits, we will cover them in the next part of this tutorial shortly.

Leave a Comment