- Hadoop Blogs -

Scala Tutorial Guide for Begginner

Introduction of Scala

Scala is an excellent choice for programmers who want to simplify coding for OOPs projects but want to still stick to fundamental programming. In this blog for Scala Tutorial, you will get a depth understanding of Scala concepts and how to learn Scala in just the right way. Whether you work with C, C++, or Java, Scala-based frameworks are widely popular for their speed and performance. With a simple and easy syntax, Scala runs over the JVM and brings efficient ways of handling huge datasets. Here, you will get all necessary details to learn Scala and take the plunge towards making a career in Scala.

Scala vs. Java: Which one to choose?

Scala is a smooth integration of functional and object-oriented languages that stimulates Java programmers to be more productive and concise. It reduces the code snippets to two-three times and minimizes the overall burden over programmers when compared with other similar programming languages. The highlighting features of Scala programming language can be given as improved computing speed, fewer lines of code, powerful, and more flexible.

Let us have a quick on the comparison Scala vs. Java and how Scala is better than the Java.

Features Scala Java
Syntax Regular Complex
Level of Ease Easy Lengthy
Orientation Functional & Object-Oriented Object-Oriented

Here are a few more features that allow Scala to rule the big data world.

  • It is made up of a consistent and powerful abstraction of types and values.
  • It can support XML documents by generalizing patterns and expressions.
  • Pattern matching concept in Scala helps in decomposing of objects.

Scala is a different flavor of Java with an effective merging of object-oriented and functional programming. This Scala tutorial will help you to master the Scala basics and get deeper insights into the advanced modules of programming to analyze or manage the huge datasets.

Here, you could learn about Arrays, strings, loops, classes, objects, collection, conditional statements, functions, and closures in Scala. It also equips you with core functionalities of File Input and Output operations, regular expressions, pattern matching, or exceptional handling, etc.

In the first place, you will learn about Scala installation them we can proceed with Scala programming basics. With Scala training, you can write programs in Scala with more proficiency and efficiency. Scala enables you to deal with modern-day big data analytics and provides effective solutions to manage tough big data problems. To get a quick idea of the syllabus, what should you actually learn during Scala online training, check this.

Recommended Audience

  • It is designed for everyone who wants to learn Scala at the global level. It promises great learning from beginners to intermediate and advanced-level programmers currently working in Java, C++, or Python.
  • It is suitable for software engineers who want to enhance their existing knowledge base and eager to learn concepts for big data processing.
  • It is suitable for ETL developers and Data Engineers as well.
  • It is good for analytics professionals and Data Scientists.
  • It is recommended for graduates who aim at learning efficient programming language for processing big data in an easy and faster manner.

Prerequisites

  • If you are already familiar with OOPs concepts or Java syntax and related programming components, then Scala can be grasped quickly.
  • In case you are not familiar with Java or belong to the non-IT background, then you have to spend more time than usual.
  • So, knowledge of object-oriented programming languages is considered an asset here.

Let us start with Scala basics in this blog now:

What is Scala?

Scala means scalable language that was created by Martin Odersky, and it was first released in 2003. It is a modern multi-paradigm programming language that combines object-oriented and functional programming concepts together. It makes it easy to design complex systems and adapt them to new demands. The syntax of Scala is very much similar to C and Java, like class libraries, basic types, and its execution model too. Scala is basically designed to represent the general programming patterns more elegantly and safely. There are two features of Scala:

  1. Functional &
  2. Object-oriented

These two features make Scala more robust and scalable. Scala features in detail are discussed below in the next section.

Scala Features

Every programming language has a set of features that makes it more suitable and better than others. Let us see what makes Scala different from other programming languages.

A). Type Inference:

It means Scala automatically infers the data of expression either fully or partially. We don’t have to declare it, and it does not impact the type checking. It aggregates the information further to decide on the type for the entire expression.

B). Immutability:

All variables are immutable by default in Scala. They cannot be modified, but if you declare them mutable, then they can be modified based on the requirement. This property of Scala helps with concurrency control further.

C). Lazy Evaluation:

If there is some expression declared lazy with the lazy keyword, then Scala delays complex computations by evaluating an expression until we don’t need it. It can also be named as call-by-need technique in Scala. The repeated evaluations can be avoided with this technique, and a few more benefits of this technique are given below:

  • Better control flow with lazy evaluation.
  • Infinite data structures can be defined potentially.
  • The overall performance can be improved.

Here is a quick example for your reference.

lazy val images=getImages()

D). Singleton Object

In Scala, there are no static variables or method, but you have to work with Singleton Object. It is a class with a single object in the source file. You can use “object” keyword to declare Singleton Objects in Scala.

object main extends app {
printIn ("Hello, World!")
}

E). Pattern Matching & Case Classes

A regular class is immutable in nature by default, and it can be made decomposable by pattern matching technique that is a case class. Parameters of a case class are immutable and public by default. Its parameters are defined through “case class” keyword and parameters of a case class can be empty sometimes.

case class Book (isbn: String)
Val frankenstein = Book ("978-000123001")

With pattern matching technique, you can compare a value against a pattern.it is like a switch statement or If-else condition in Java.

import scala.util.Random
val x: Int = Random.nextInt(10)
x match
{
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "many"
}

F). String Interpolation

It is a form of template processing. String Interpolation means string evaluation consisting of one or more placeholders to yield the output. String interpolation method was introduced in later versions of Scala and used extensively by programmers these days.

G). Concurrency Control

Scala has a set of tools or frameworks further that can be used to achieve the concurrency. It is possible combining different frameworks or tools together as per the requirement.

H). Traits

A train can be defined as the type holding different fields and methods. Traits are usually defined with the “trait” keyword.

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

It can be taken as the partially implemented interface. You can define a trait with abstract and non-abstract methods. It is possible combining multiple traits together if required.

I). Higher-order Functions

With the help of these functions, other functions can be returned or they can be defined as a parameter. Scala makes it possible by treating their functions as first-class citizens. Here is one simple example for your reference.

val salaries = Seq(20000, 70000, 40000)
val doubleSalary = (x: Int) => x * 2
val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000)

Look at the example carefully; you will notice that the map is a high-order function. With the help of high-order functions, you can implement function compositions and lambdas.

J). A rich set of collection

The Scala library has a huge set of collections with classes and traits that help in collecting data into a mutable and immutable format. The immutable package in Scala holds all immutable data, and it cannot be modified. Likewise, there is one mutable package that holds all mutable data.

K). Functional Programming Language

Scala is a functional programming language that utilizes traits, high-order functions, and more. Other than this, it supports nested functions and methods. It also helps in evaluating a function that contains multiple arguments.

L). Object-oriented Language

Scala is an object-oriented language and also being functional. In Scala, every value is an object.

M). Statically-typed

You don’t have to declare any redundant type of information in your code. Scala can decide that based on subexpressions, atomic values, and more. It is in pertinence to type interference.

N). Extensibility

When you want to build domain-specific apps, you need domain-specific language extensions too. Scala allows you are adding new language constructs as libraries. Constructs like string interpolation and implicit classes help us to do this. Here, we don’t need any meta-programming features like Macros.

O). JVM

With the help of compiler, source code can be converted to Java bytecode that runs over the JVM, Java Virtual Machine. With this discussion, you must be aware of Scala features and how it is different from existing programming languages. Moving ahead, let us learn Scala Frameworks or development tools that can be used extensively with a project.

Scala Frameworks or Development Tools

With this section, you will learn different frameworks or a set of development tools that can be used with Scala.

1). Akka

It is an open-source toolkit that simplifies constructing concurrent and distributed apps on JVM. Akka is good with the distributed programming.

2). Apache Kafka

It is an open source stream processing software by Apache Foundation. It is written in Scala and Java. With Kafka, you can achieve high throughput, low-latency platform to handle real-time apps. It is good for distributed processing, generally.

3). Scala Query

It is a low-level Scala API for database access, compile-time checking, and type-safety. The JDBC API is powerful but verbose.

4). Squeryl

It is a DSL to manipulate database objects from within the Scala. It is similar to SQL that is strongly-typed and declarative in nature.

5). Lift

It is a free and open source web framework in Scala.  It was created to remove the drawbacks of Ruby on Rails.

6). Play

It is an open-source web framework written in Scala.

7). Scalatra

It is an open-source and free web framework written in Scala. It can be used alternatively to the Lift or Play. Next topic in Scala Tutorial is how to install Scala. Read all the steps carefully and perform them one by one to install Scala on your system successfully.

Scala Installation

Before installing Scala, you should Java 1.5 version or higher on your system.

Step 1: Verify the JDK installation on your machine first. For this purpose, open the terminal and write java -version and javac -version. This command will tell you which JDK version is installed. If it is not installed, then install it now before you jump to the next step.

Step 2: Now download the Scala from the web link - http://www.scala-lang.org/download/ and run the downloaded file.

Scala

Step 3: Click on Next button, select the check box. If you want to change the location where you want to save the folder then make the changes otherwise click on Next.

Scala

Step 4: Click on Install button, and the installation process will start immediately. Please keep patience because it may take time. Once it is done, click the Finish button.

Scala

Step 5: Set the Scala directory path and type Scala in command line prompt to start using it.

Scala

With these few simple steps, Scala can be installed on your Windows operating system quickly. It can be installed on other operating systems as well like Linux or MAC when required. Steps are almost the same, but your knowledge of command line prompt needs to be little stronger in that case.

Hello Program in Scala

Before you start writing your first program in Scala, evaluate your skills on the platform with this quiz now.

It includes compiler and interpreter both when writing a program in Java. The compiler will generate a class file first which is a binary file, and it can be executed with the help of JVM. At the same time, the interpreter executes the code given in a text file that can be used interactively with Scala. A simple program in Scala can be written as:

object HelloJanBask {
def main(args: Array[String]) {
println("Hello JanBask")
} }

You have to write this code on command line prompt where main is a pre-defined function and code is saved in a file with the name HelloJanBask.scala. Further, the command that can be used to execute the source code is given below.

$ scalac HelloJanBask.scala
$ scala HelloJanBask

Output

Hello JanBask

This is clear from the example that it is easy to switch to Scala if your basic understanding of the Java programming language and you have worked on Java programs earlier.

Basic types in Scala

Objects with no internal structure and no components are said to be of basic types in Scala. Usually, a Scala program describes the interaction between objects and helps in exchanging messages. For example, numbers, strings, or character can interact together with similar or different types of objects.

Here are basic types in Scala for your reference:

Data Type & Description

Byte

8 bit signed value. Range from -128 to 127

Short

16 bit signed value. Range -32768 to 32767

Int

32 bit signed value. Range -2147483648 to 2147483647

Long

64 bit signed value. -9223372036854775808 to 9223372036854775807

Float

32 bit IEEE 754 single-precision float

Double

64 bit IEEE 754 double-precision float

Char

16 bit unsigned Unicode character. Range from U+0000 to U+FFFF

String

A sequence of Chars

Boolean

Either the literal true or the literal false

Unit

Corresponds to no value

Null

null or empty reference

Nothing

The subtype of every other type; includes no values

Any

The supertype of any type; any object is of type Any

AnyRef

The supertype of any reference type

Operators in Scala

Operators are symbols that perform operations on some values. These values can also be named as operands. Here are a few operators in Scala you should know:

  • Arithmetic Operators: Arithmetic operators in Scala are used to perform simple mathematical calculations. They can be given as addition, subtraction, multiplication, divide, or modulus, etc.
  • Relational Operators: They can also be named as comparison operators and used to compare the values. After comparing the values, it returns Boolean output either True or False. A few common relational operators in Scala are Equal to, Not Equal to, Less than, Greater than, Less than equal to, greater than equal to, etc.
  • Logical Operators: These operators are used to implement the logic in Scala. A few common logical operators are And, Or, Not, etc. when both conditions are true, use “AND” operator. When either one condition is true, and another is False, use “OR” operator. To reverse the condition, “NOT” operator is used in Scala.
  • Assignment Operators: These operators are used to assign values either directly, or you have to perform some operation then add the value to the variable. There are many assignment operators you can use as per the requirement.
  • Bitwise Operators: It performs bit by bit operations. It is a little complex, and you should enroll for the training program to learn using these operators.

Scala Applications

So, you must be wondering what we can do with Scala? Here are some of the things that you may build with Scala.

  • Android apps, Desktop apps
  • Front and backends of web apps.
  • Distributed data processing, concurrency control, etc.
  • High concurrent apps like messaging or more with Akka.
  • Distributing computing is another feature that can be achieved with Scala.
  • Scala can be combined with Hadoop for MapReduce programs.
  • Analyze or process Big Data with Apache Spark.
  • Achieve data streaming with Akka.
  • Other applications are parallel batch processing, AWS lambda expression, Ad hoc scripting, etc.

Array in Scala

An Array can be defined as the mutable object in Scala that can be modified. It is taken as the collection of elements having the same types. They are further associated with an index that can be used to access or replace any particular element. An array is implemented as several consecutive memory locations that are indexed by consecutive numbers.

In Scala, arrays are objects, and there are several objects associated with each object. Basically, an array can be defined in two ways when it comes to Scala.

  • First, it specifies the total number of elements and assigns values to each element.
  • Further, it specifies all values together at once.

Here is one quick example for your reference.

var i: array [String] = new array [String](5)

Here, “I” is declared as an array of string that holds up to five elements. An array can also be declared as given below.

var i = new array [string](5)

Strings in Scala

A string in Scala is an immutable object that cannot be modified. Each element in a string is given an index number. Index starts with “0” and moves on one by one. There are multiple predefined string functions and methods that can be used to perform different operations on the string.

var i = "janbasktraining"

A few string methods are:

Length: it returns the number of Unicode units within a string.

printIn (i.length)

Char at: This method has the index number and returns the “char at” the specified index.

printIn (i.charAt(2))

Starts with: It will check either the string starts with the argument of method or not.

printIn (A.startswith("i"))

Ends with: It will check either the string ends with the argument of method or not.

printIn (i.endwith("i"))

Index of: it returns the index within the string object of the first occurrence of the string argument.

printIn (i.indexOf("n"))

Concat: This method is used to append one string with another one. In simple words, it is used to combine two strings.

I = i.concat ("Hello");

PrintIn (A)

Substring: it is a new string that is the substring of the given string. It may take or two or more arguments together. It works on index values. So, you should define them carefully for accurate results.

PrintIn(I.Substring(1,4))

Contains: it will check either a string contains the particular substring or not.

if(I.contains ("inte"))

PrintIn("Contains specified string")

Replace: it takes two arguments where one argument can be replaced with another one.

PrintIn(I.replace('a','t'))

PrintIn(i)

Lower case: It converts the complete string to lower cases.

PrintIn(I.toLowerCase())

Upper Case: It converts the complete string to upper cases.

PrintIn(I.toUpperCase())

Trim: It returns the copy of the string by eliminating whitespaces.

Here, we have discussed frequently used string functions in Scala. However, the list is long and if you want to know all of them practically then join Scala certification course at JanBask Training now.

Scala Collections

Collections can be defined as containers that contain a random number of elements. Most collection classes are available in a collection package. They can be divided into two categories further: these are Mutable collections and immutable collections.

  • Mutable collection can be changed, once it is created. All mutable classes are available in the mutable collection package.
  • Immutable collection can never be changed, once it is created. All immutable classes are available in the immutable collection package.

Some most common collection types in Scala are:

List: The list is a collection of similar type of elements that are immutable in nature. The term Linked List can better understand it. Here is the quick representation of List for your reference.

List[t]

To represent an empty list, you may use the keyword empty.

Map: it is a collection of key-value pairs where the key is unique, and value can be retrieved according to the key.  There are mutable and immutable versions of Map that can be used according to requirement.  The “Map” is immutable by default if you want to make it mutable then add a mutable keyword in the beginning.

var I:Map[String, int] = Map() //Creates empty hash table whose values are integers and keys are string type
val data = map( 'a'->10, 'b'->20, 'c'->30, 'd'->40)

The following three techniques can represent all operations on Map.

  1. Key: It returns each key in the map.
  2. Value: It returns each value in the map.
  3. Is Empty: it returns true if the map is empty otherwise false.

Set: It represents the collection of elements that are of the same type but don’t contain the same elements. By default, a set is immutable in Scala. If you want to use mutable set, then you can write “mutable.set” to make it editable.

var i : Set[Int] = set() //empty set of integer type
var i : Set[Int] = Set(10, 20, 30, 40) //Set of Integer type

All operations on Sets can be represented by the following three techniques.

  1. Head: It returns the first element of the set.
  2. Tail: It returns the complete set except for the first element.
  3. Is Empty: It returns true if the set is empty otherwise false.

Tuples: It is the collection of the heterogeneous type of objects that combines a fixed number of elements together. Here is the basic syntax of tuples for your reference.

val i = (1, "JanBaskTraining")

Iterators: It is used to access elements of the collection one by one. Two most important types of iterators can be given as:

  1. Next
  2. Has next

Next is used to return the next element of the iterator and move ahead of the state of iterator. The “has next” iterator will check either there are more elements to return or not.

Final Words:

In this blog for Scala Tutorial, we tried to cover all basic concepts, but it cannot be considered a complete guide to Scala. To know about Scala in depth and practical aspects of programming language, you may join the Scala Certification course at JanBask Training. We start the training from basics, and once you are confident about the platform, then you can switch to advanced topics.

You can request for a demo class before the final registration. It will give you an idea of the online learning environment and our mentors too. If you are sure, then you can join the training program with more confidence and a planned move — all the best for a successful career in Scala domain.

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Comments

Search Posts

Reset

Receive Latest Materials and Offers on Hadoop Course