Scala is a general-purpose programming language that combines both object-oriented and functional programming. Designed for scalability and flexibility, it allows developers to write concise and maintainable code for everything from small scripts to large enterprise systems. First released in June 2004, with the latest stable version being Scala 2.12.6, released on April 27, 2018.
Scala is:
- A high-level, multi-paradigm language that supports both pure object-oriented and functional programming styles.
- Compiled to JVM bytecode, meaning Scala programs run on the Java Virtual Machine (JVM) and can easily use Java libraries.
- Short for "Scalable Language", built to grow with the size and complexity of your projects.

Getting Started With Scala
Scala programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Scala codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.
To begin with, writing Scala Codes and performing various intriguing and useful operations, one must have scala installed on their system. This can be done by following the step by step instructions provided below:
Verifying Java Packages
The first thing we need to have is a Java Software Development Kit (SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them.
Now install Scala
As we are done with installing the java, now let's install the scala packages. The best option to download these packages is to download from the official site only: https://www.scala-lang.org/download/
The packages in the link above is the approximately of 100MB storage. Once the packages are downloaded then open the downloaded .msi file.
Testing and Running the Scala Commands
Open the command prompt now and type in the following codes:
C:\Users\Your_PC_username>scala
We will receive an output as shown below:

If you get this output without any error, then you have installed Scala successfully.
First Scala Program
Here is a simple Scala code, printing a string. We recommend you to edit the code and try to print your own name.
Scala
// Scala program to print Hello World
// Creating object
object Geeks {
// Main method
def main(args: Array[String])
{
// prints Hello, Geeks!
println("Hello, World!")
}
}
Output:
Hello, World!
Open Command line and then to compile the code type Scala Hello.scala. If your code has no error then it will execute properly and output will be displayed:

Variables
Variables are simply a storage location. Every variable is known by its name and stores some known and unknown piece of information known as value. In Scala there are two types of variable:
- Mutable Variables: These variables are those variables which allow us to change a value after the declaration of a variable. Mutable variables are defined by using the "var" keyword.
- Immutable Variables: These variables are those variables which do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the "val" keyword.
Example:
// Mutable Variable
var name: String = "geekforgeeks";
// Immutable Variable
val name: String = "geekforgeeks";
To learn Scala Variables refer - Variables in Scala, Scope of Variable in Scala.
Operator
An operator is a symbol that represents an operation to be performed with one or more operand. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Bitwise Operators
Example :
Scala
// Scala program to demonstrate
// the Operators
// Creating object
object Geeks
{
// Main method
def main(args: Array[String])
{
// Operands
var a = 10;
var b = 4;
var c = true;
var d = false;
var result = 0;
// using arithmetic operators
println ("Addition is: "+ (a + b) );
println ("Subtraction is: "+ (a - b) ) ;
// using Relational Operators
if (a == b)
{
println ("Equal To Operator is True");
}
else
{
println ("Equal To Operator is False");
}
// using Logical Operator 'OR'
println("Logical Or of a || b = " + (c || d));
// using Bitwise AND Operator
result = a & b;
println ("Bitwise AND: " + result );
// using Assignment Operators
println ("Addition Assignment Operator: " + (a += b) );
}
}
OutputAddition is: 14
Subtraction is: 6
Equal To Operator is False
Logical Or of a || b = true
Bitwise AND: 0
Addition Assignment Operator: ()
To learn Scala Operators, refer - Operators in Scala
Decision Making
Decision Making in programming is similar to decision making in real life. Scala uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
Decision Making Statements in Scala:
- If
- If - else
- Nested – If
- if - elsif ladder
Example 1: To illustrate use of if and if-else
Scala
// Scala program to illustrate the if and if-else statement
object Test
{
// Main Method
def main(args: Array[String])
{
// taking a variable
var a: Int = 650
// if condition to check
// for even number
if(a % 2 == 0)
{
println("Even Number")
}
if (a > 698)
{
// This statement will not
// execute as a > 698 is false
println("GeeksforGeeks")
}
else
{
// This statement will execute
println("Sudo Placement")
}
}
}
OutputEven Number
Sudo Placement
Example 2: To illustrate the use of Nested-if
Scala
// Scala program to illustrate
// Nested if statement
object Test
{
// Main Method
def main(args: Array[String])
{
var a: Int = 10;
if(a % 2 == 0)
{
// Nested - if statement
// Will only be executed
// if above if statement
// is true
if(a % 5 == 0)
{
println("Number is divisible by 2 and 5\n")
}
}
}
}
OutputNumber is divisible by 2 and 5
To know more about Decision Making please refer to Decision making in Scala
Loops
In Scala, loops are used to execute a block of code multiple times—just like in other programming languages. However, Scala encourages a more functional approach (like using map
, foreach
, filter
, etc.), but it still supports traditional loops. The loops in Scala are:
1. for loop :
Scala
// Scala program to illustrate for loop
object forloopDemo {
// Main Method
def main(args: Array[String]) {
var y = 0;
// for loop execution with range
for(y <- 1 to 4)
{
println("Value of y is: " + y);
}
}
}
OutputValue of y is: 1
Value of y is: 2
Value of y is: 3
Value of y is: 4
2. While loop :
Scala
// Scala program to illustrate while loop
object whileLoopDemo
{
// Main method
def main(args: Array[String])
{
var x = 1;
// Exit when x becomes greater than 4
while (x <= 4)
{
println("Value of x: " + x);
// Increment the value of x for
// next iteration
x = x + 1;
}
}
}
OutputValue of x: 1
Value of x: 2
Value of x: 3
Value of x: 4
3. do-while loop :
Scala
// Scala program to illustrate do..while loop
object dowhileLoopDemo
{
// Main method
def main(args: Array[String])
{
var a = 10;
// using do..while loop
do
{
print(a + " ");
a = a - 1;
}while(a > 0);
}
}
Output10 9 8 7 6 5 4 3 2 1
To know more about Loops please refer to Loops in Scala
Arrays
Array is a special kind of collection in Scala. it is a fixed size data structure that stores elements of the same data type. It is a collection of mutable values. Below is the syntax.
Syntax :
var arrayname = new Array[datatype](size)

It will create an array of integers which contains the value 40, 55, 63, 17 and many more. Below is the syntax to access a single element of an array, if we've created an array named number.
number(0)
It will produce the output as 40.
Iterating through an Array:
In this example we create an array while providing the values of its elements at the same time. In this case, the type is inferred.
Scala
// Scala program to accessing an array
// of the string as name.
object GFG
{
// Main method
def main(args: Array[String])
{
// allocating memory of 1D Array of string.
var name = Array("gfg", "geeks", "GeeksQuize",
"geeksforgeeks" )
println("second element of an array is: ")
// Accessing an array element
println(name(1) )
}
}
Outputsecond element of an array is:
geeks
To know more about arrays please refer to Arrays in Scala
String
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In Scala a String type is specified before meeting the string literal. but when the compiler meet to a string literal and creates a string object str.
Syntax :
var str = "Hello! GFG"
or
val str = "Hello! GFG"
var str: String = "Hello! GFG"
or
val str: String = "Hello! GFG"
Scala
// Scala program to illustrate how to
// create a string
object Main
{
// str1 and str2 are two different strings
var str1 = "Hello! GFG"
val str2: String = "GeeksforGeeks"
def main(args: Array[String])
{
// Display both strings
println(str1);
println(str2);
}
}
OutputHello! GFG
GeeksforGeeks
Concatenating Strings in Scala:
When a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. You can also use ‘+’ operator to concatenate two strings.
Scala
// Scala program to illustrate how to
// concatenate strings
object Main
{
// str1 and str2 are two strings
var str1 = "Welcome! GeeksforGeeks "
var str2 = " to Portal"
// Main function
def main(args: Array[String])
{
// concatenate str1 and str2 strings
// using concat() function
var Newstr = str1.concat(str2);
// Display strings
println("String 1:" +str1);
println("String 2:" +str2);
println("New String :" +Newstr);
// Concatenate strings using '+' operator
println("This is the tutorial" +
" of Scala language" +
" on GFG portal");
}
}
OutputString 1:Welcome! GeeksforGeeks
String 2: to Portal
New String :Welcome! GeeksforGeeks to Portal
This is the tutorial of Scala language on GFG portal
To know more about Strings please refer to Strings in Scala
Functions
A function is a collection of statements that perform a certain task. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values. Below is the syntax of Scala Functions.
Syntax:
def function_name ([parameter_list]) : [return_type] = {
// function body
}
In the above code, def keyword is used to declare a function in Scala.
Function Calling : There are mainly two ways to call the function in Scala. First way is the standard way as follows:
function_name(paramter_list)
In the Second way, a user can also call the function with the help of the instance and dot notation as follows:
[instance].function_name(paramter_list)
Scala
// Scala program of function calling
object GeeksforGeeks {
def main(args: Array[String]) {
// Calling the function
println("Sum is: " + functionToAdd(5, 3));
}
// declaration and definition of function
def functionToAdd(a:Int, b:Int) : Int =
{
var sum:Int = 0
sum = a + b
// returning the value of sum
return sum
}
}
Output :
Sum is: 8
Anonymous Functions in Scala :
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function.
Syntax :
(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)
Scala
// Scala program to illustrate the anonymous method
object Main
{
def main(args: Array[String])
{
// Creating anonymous functions
// with multiple parameters Assign
// anonymous functions to variables
var myfc1 = (str1:String, str2:String) => str1 + str2
// An anonymous function is created
// using _ wildcard instead of
// variable name because str1 and
// str2 variable appear only once
var myfc2 = (_:String) + (_:String)
// Here, the variable invoke like a function call
println(myfc1("Geeks", "12Geeks"))
println(myfc2("Geeks", "forGeeks"))
}
}
Output :
Geeks12Geeks
GeeksforGeeks
Scala Nested Functions:
A function definition inside an another function is known as Nested Function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions.
Syntax :
def FunctionName1( perameter1, peramete2, ..) = {
def FunctionName2() = {
// code
}
}
Scala
// Scala program of Single Nested Function
object MaxAndMin
{
// Main method
def main(args: Array[String])
{
println("Min and Max from 5, 7")
maxAndMin(5, 7);
}
// Function
def maxAndMin(a: Int, b: Int) = {
// Nested Function
def maxValue() = {
if(a > b)
{
println("Max is: " + a)
}
else
{
println("Max is: " + b)
}
}
// Nested Function
def minValue() = {
if (a < b)
{
println("Min is: " + a)
}
else
{
println("Min is: " + b)
}
}
maxValue();
minValue();
}
}
Output:
Min and Max from 5, 7
Max is: 7
Min is: 5
Currying Functions in Scala :
Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument.
Syntax :
def function name(argument1, argument2) = operation
Scala
// Scala program add two numbers
// using currying Function
object Curry
{
// Define currying function
def add(x: Int, y: Int) = x + y;
def main(args: Array[String])
{
println(add(20, 19));
}
}
Output:
39
Object Oriented Programming
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
OOP's Concepts:

Creation of a Class and an Object:
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created.
Scala
// A Scala program to illustrate
// how to create a class
// Name of the class is Smartphone
class Smartphone
{
// Class variables
var number: Int = 16
var nameofcompany: String = "Apple"
// Class method
def Display()
{
println("Name of the company : " + nameofcompany);
println("Total number of Smartphone generation: " + number);
}
}
object Main
{
// Main method
def main(args: Array[String])
{
// Class object
var obj = new Smartphone();
obj.Display();
}
}
OutputName of the company : Apple
Total number of Smartphone generation: 16
Traits
Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members.
Creating a trait -
Scala
// Scala program to illustrate how to
// create traits
// Trait
trait MyTrait
{
def pet
def pet_color
}
// MyClass inherits trait
class MyClass extends MyTrait
{
// Implementation of methods of MyTrait
def pet()
{
println("Pet: Dog")
}
def pet_color()
{
println("Pet_color: White")
}
// Class method
def pet_name()
{
println("Pet_name: Dollar")
}
}
object Main
{
// Main method
def main(args: Array[String])
{
val obj = new MyClass();
obj.pet();
obj.pet_color();
obj.pet_name();
}
}
Output :
Pet: Dog
Pet_color: White
Pet_name: Dollar
To know more about Traits please refer to Traits in Scala
Regular Expression
Regular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex.
Scala
// Scala program for Regular
// Expressions
// Creating object
object GfG
{
// Main method
def main(args
: Array[String])
{
// Applying r() method
val portal = "GeeksforGeeks".r
val CS
= "GeeksforGeeks is a CS portal."
// Displays the first match
println(portal findFirstIn CS)
}
}
Output :
Some(GeeksforGeeks)
To know more about tuple please refer to Regular Expressions in Scala.
Exception
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution.

In Scala, all exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.
The Throwing Exceptions :
Scala
// Scala program of throw keyword
// Creating object
object Main
{
// Define function
def validate(article:Int)=
{
// Using throw keyword
if(article < 20)
throw new ArithmeticException("You are not eligible for internship")
else println("You are eligible for internship")
}
// Main method
def main(args: Array[String])
{
validate(22)
}
}
Output :
You are eligible for internship
Try-Catch Exceptions :
Scala
// Scala program of try-catch Exception
import java.io.IOException
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
try
{
var N = 5/0
}
catch
{
// Catch block contain cases.
case i: IOException =>
{
println("IOException occurred.")
}
case a : ArithmeticException =>
{
println("Arithmetic Exception occurred.")
}
}
}
}
Output :
Arithmetic Exception occurred.
File Handling
File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we don’t have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter.
Creating a new file :
- java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.
- File(String pathname) converts theparameter string to abstract path name, creating a new file instance.
Writing to the file :
- java.io.PrintWriter includes all the printing methods included in PrintStream.
- Below is the implementation for creating a new file and writing into it.
Scala
// Scala File handling program
import java.io.File
import java.io.PrintWriter
// Creating object
object Geeks
{
// Main method
def main(args:Array[String])
{
// Creating a file
val file_Object = new File("abc.txt" )
// Passing reference of file to the printwriter
val print_Writer = new PrintWriter(file_Object)
// Writing to the file
print_Writer.write("Hello, This is Geeks For Geeks")
// Closing printwriter
print_Writer.close()
}
}

Reading a File :
Below is the example to reading a file.
Scala
// Scala File handling program
import scala.io.Source
// Creating object
object GeeksScala
{
// Main method
def main(args : Array[String])
{
// file name
val fname = "abc.txt"
// creates iterable representation
// of the source file
val fSource = Source.fromFile(fname)
while (fSource.hasNext)
{
println(fSource.next)
}
// closing file
fSource.close()
}
}

To know more about various different File Handling, please refer to File Handling in Scala
List in Scala
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable whereas arrays are mutable in Scala. In a Scala list, each element must be of the same type. list is defined under scala.collection.immutable package.
Syntax :
val variable_name: List[type] = List(item1, item2, item3)
or
val variable_name = List(item1, item2, item3)
Create and initialize Scala List
Example :
Scala
// Scala program to print immutable lists
import scala.collection.immutable._
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
// Creating and initializing immutable lists
val mylist1: List[String] = List("Geeks", "GFG",
"GeeksforGeeks", "Geek123")
val mylist2 = List("C", "C#", "Java", "Scala",
"PHP", "Ruby")
// Display the value of mylist1
println("List 1:")
println(mylist1)
// Display the value of mylist2 using for loop
println("\nList 2:")
for(mylist<-mylist2)
{
println(mylist)
}
}
}
Output :
List 1:
List(Geeks, GFG, GeeksforGeeks, Geek123)
List 2:
C
C#
Java
Scala
PHP
Ruby
To know more about List please refer to List in Scala.
Map
Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly.
Creating a Map and accessing the value
Example :
Scala
// Scala map program of
// Accessing Values Using Keys
// Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
val mapIm = Map("Ajay" -> 30,
"Bhavesh" -> 20,
"Charlie" -> 50)
// Accessing score of Ajay
val ajay = mapIm("Ajay")
println(ajay)
}
}
Output :
30
To know more about Map please refer to Map in Scala.
Iterator
An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. To access elements we can make use of hasNext() to check if there are elements available and next() to print the next element.
Syntax:
val v = Iterator(5, 1, 2, 3, 6, 4)
//checking for availability of next element
while(v.hasNext)
//printing the element
println(v.next)
Example :
Scala
//Scala iterator program
//for defining iterator
//Creating object
object GFG
{
// Main method
def main(args:Array[String])
{
val v = Array(5, 1, 2, 3, 6, 4)
//val v = List(5, 1, 2, 3, 6, 4)
// defining an iterator
// for a collection
val i = v.iterator
while (i.hasNext)
print(i.next + " ")
}
}
Output:
5 1 2 3 6 4
To know more about tuple please refer to Iterators in Scala.
Set
A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request.
Syntax :
// Immutable set
val variable_name: Set[type] = Set(item1, item2, item3)
or
val variable_name = Set(item1, item2, item3)
// Mutable Set
var variable_name: Set[type] = Set(item1, item2, item3)
or
var variable_name = Set(item1, item2, item3)
Creating and initializing Immutable set
Example :
Scala
// Scala program to illustrate the
// use of immutable set
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing immutable sets
val myset1: Set[String] = Set("Geeks", "GFG",
"GeeksforGeeks", "Geek123")
val myset2 = Set("C", "C#", "Java", "Scala",
"PHP", "Ruby")
// Display the value of myset1
println("Set 1:")
println(myset1)
// Display the value of myset2 using for loop
println("\nSet 2:")
for(myset<-myset2)
{
println(myset)
}
}
}
Output :
Set 1:
Set(Geeks, GFG, GeeksforGeeks, Geek123)
Set 2:
Scala
C#
Ruby
PHP
C
Java
Creating and initializing mutable set
Example :
Scala
// Scala program to illustrate the
// use of mutable set
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
// Creating and initializing mutable sets
var myset1: Set[String] = Set("Geeks", "GFG",
"GeeksforGeeks", "Geek123")
var myset2 = Set(10, 100, 1000, 10000, 100000)
// Display the value of myset1
println("Set 1:")
println(myset1)
// Display the value of myset2
// using a foreach loop
println("\nSet 2:")
myset2.foreach((item:Int)=>println(item))
}
}
Output :
Set 1:
Set(Geeks, GFG, GeeksforGeeks, Geek123)
Set 2:
10
100000
10000
1000
100
To know more about Set please refer to Set in Scala | Set-1 and Set in Scala | Set-2.
Tuple
Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in Scala which is mutable.
Creating a tuple and accessing an element
Example :
Scala
// Scala program to access
// element using underscore method
// Creating object
object gfg
{
// Main method
def main(args: Array[String])
{
var name = (15, "chandan", true)
println(name._1) // print 1st element
println(name._2) // print 2nd element
println(name._3) // print 3st element
}
}
Output :
15
chandan
true
To know more about tuple please refer to tuple in Scala.
This article has covered the most important concepts of Scala, helping you build a solid foundational understanding of the language. It explored all the essential topics such as arrays, strings, tuples, loops, lists, operators, and file handling, equipping you with the core skills needed to start working with Scala effectively.
For more, you can also refer to: Scala Programming Language
Similar Reads
Overview
Basics
Control Statements
Scala | Decision Making (if, if-else, Nested if-else, if-else if)Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Scala uses control statements to control the flow of execution of the prog
5 min read
Scala | Loops(while, do..while, for, nested loops)Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loop to handle the condition based situation in the progr
5 min read
Break statement in ScalaIn Scala, we use a break statement to break the execution of the loop in the program. Scala programming language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop
3 min read
Scala | LiteralsAny constant value which can be assigned to the variable is called as literal/constant. The literals are a series of symbols utilized for describing a constant value in the code. There are many types of literals in Scala namely Character literals, String literals, Multi-Line String literals, Boolean
4 min read
OOP Concepts
Methods
Strings
Scala Packages
Scala Trait
Collections
Scala ListsA list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala: Lists are immutable whereas arrays are mutable in Scala. Lists represents
5 min read
Scala ListBufferA list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer. The Scala List class holds a sequenced, linear list of items. A List can be built u
6 min read
ListSet in ScalaA set is a collection which only contains unique items which are not repeatable and a list is a collection which contains immutable data. In scala, ListSet class implements immutable sets using a list-based data structure. Elements are stored in reversed insertion order, That means the newest elemen
6 min read
Scala MapMap is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. Key-value pairs can have any data type. However, data type once used for any key and value must be consistent throughout. Maps are classified into two types: m
5 min read
Scala | ArraysArray is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values. It corresponds to arr
6 min read
Scala | ArrayBufferArray in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size canât change. To create a mutable, indexed sequence whose size can change ArrayBuffer class is used. To use, ArrayBuffer, scala.collection.mutable.ArrayBuf
4 min read
Scala | TupleTuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
5 min read
Set in Scala | Set-1A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax: // Immutable set val variable_name: Set[type] = Set(item1, item2, ite
3 min read
Set in Scala | Set-2Prerequisite: Set in Scala | Set-1Adding items in Mutable SetIn Set, We can only add new elements in mutable set. +=, ++== and add() method is used to add new elements when we are working with mutable set in mutable collection and += is used to add new elements when we are working with mutable set i
7 min read
BitSet in ScalaA set is a collection which only contains unique items which are not repeatable. A BitSet is a collection of small integers as the bits of a larger integer. Non negative integers sets which represented as array of variable-size of bits packed into 64-bit words is called BitSets. The largest number s
5 min read
HashSet In ScalaHashSet is sealed class. It extends immutable Set and AbstractSet trait. Hash code is used to store elements. It neither sorts the elements nor maintains insertion order . The Set interface implemented by the HashSet class, backed by a hash table . In Scala, A concrete implementation of Set semantic
4 min read
Stack in ScalaA stack is a data structure that follows the last-in, first-out(LIFO) principle. We can add or remove element only from one end called top. Scala has both mutable and immutable versions of a stack. Syntax : import scala.collection.mutable.Stack var s = Stack[type]() // OR var s = Stack(val1, val2, v
3 min read
HashMap in ScalaHashMap is a part of Scala Collection's. It is used to store element and return a map. A HashMap is a combination of key and value pairs which are stored using a Hash Table data structure. It provides the basic implementation of Map. Syntax: var hashMapName = HashMap("key1"->"value1", "key2"->"value
3 min read
TreeSet in ScalaSet is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions: scala.collection.immutable.TreeSet and scala.collection.mutable.TreeSet. Syntax
4 min read
Iterators in ScalaAn iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Ther
5 min read
Scala | OptionThe Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. Important points : The insta
3 min read