TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Scala Interview Questions (2021)

Scala Interview Questions for beginners and professionals with examples. TheDeveloperBlog helps you to prepare your Scala interview with top list questions and answers.

<< Back to SCALA

Scala Interview Questions

Scala Interview Questions

1) What is Scala?

Scala is a general-purpose programming language. It supports object-oriented, functional and imperative programming approaches. It is a strong static type language. In Scala, everything is an object whether it is a function or a number. It was designed by Martin Odersky in 2004.

Scala Program Example

object MainObject{
    def main(args:Array[String]){
		print("Hello Scala")
    }
}

For more information: Click here.


2) What are the features of Scala?

There are following features in Scala:

  • Type inference: In Scala, you don't require to mention data type and function return type explicitly.
  • Singleton object: Scala uses a singleton object, which is essentially class with only one object in the source file.
  • Immutability: Scala uses immutability concept. Immutable data helps to manage concurrency control which requires managing data.
  • Lazy computation: In Scala, computation is lazy by default. You can declare a lazy variable by using the lazy keyword. It is used to increase performance.
  • Case classes and Pattern matching: In Scala, case classes support pattern matching. So, you can write more logical code.
  • Concurrency control: Scala provides a standard library which includes the actor model. You can write concurrency code by using the actor.
  • String interpolation: In Scala, string interpolation allows users to embed variable references directly in processed string literals.
  • Higher order function: In Scala, higher order function allows you to create function composition, lambda function or anonymous function, etc.
  • Traits: A trait is like an interface with partial implementation. In Scala, the trait is a collection of abstract and non-abstract methods.
  • Rich set of collection: Scala provides a rich set of collection library. It contains classes and traits to collect data. These collections can be mutable or immutable.

For more information: Click here.


3) What are the Data Types in Scala?

Data types in Scala are much similar to Java regarding their storage, length, except that in Scala there is no concept of primitive data types every type is an object and starts with capital letter. A table of data types is given below.

Data Types in Scala

Data Type Default Value Size
Boolean False True or false
Byte 0 8 bit signed value (-27 to 27-1)
Short 0 16 bit signed value(-215 to 215-1)
Char '\u0000' 16 bit unsigned Unicode character(0 to 216-1)
Int 0 32 bit signed value(-231 to 231-1)
Long 0L 64 bit signed value(-263 to 263-1)
Float 0.0F 32 bit IEEE 754 single-precision float
Double 0.0D 64 bit IEEE 754 double-precision float
String Null A sequence of characters

For more information: Click here.


4) What is pattern matching?

Pattern matching is a feature of Scala. It works same as switch case in other languages. It matches the best case available in the pattern.

Example

object MainObject {
   def main(args: Array[String]) {
        var a = 1
        a match{
            case 1 => println("One")
            case 2 => println("Two")
            case _ => println("No")
        }
        }
}

For more information: Click here.


5) What is for-comprehension in Scala?

In Scala, for loop is known as for-comprehensions. It can be used to iterate, filter and return an iterated collection. The for-comprehension looks a bit like a for-loop in imperative languages, except that it constructs a list of the results of all iterations.

Example

object MainObject {
   def main(args: Array[String]) {
        for( a <- 1 to 10 ){
         println(a);
      }
   }
}

For more information: Click here.


6) What is the breakable method in Scala?

In Scala, there is no break statement, but you can do it by using break method and importing Scala.util.control.Breaks._ package. It can break your code.

Example

import scala.util.control.Breaks._					// Importing  package
object MainObject {
   def main(args: Array[String]) {
        breakable { 								// Breakable method to avoid exception
            for(i<-1 to 10 by 2){
                if(i==7) 
                    break							// Break used here
                else
                    println(i)
            }
        }
    }
}

For more information: Click here.


7) How to declare a function in Scala?

In Scala, functions are first-class values. You can store function value, pass a function as an argument and return function as a value from other function. You can create a function by using the def keyword. You must mention return type of parameters while defining a function and return type of a function is optional. If you don't specify the return type of a function, default return type is Unit.

Scala Function Declaration Syntax

def functionName(parameters : typeofparameters) : returntypeoffunction = {
// statements to be executed
}

For more information: Click here.


8) Why do we use =(equal) operator in Scala function?

You can create a function with or without = (equal) operator. If you use it, the function will return value. If you don't use it, your function will not return anything and will work like the subroutine.

Example

object MainObject {
   def main(args: Array[String]) {
        var result = functionExample() 	    // Calling function
        println(result)
    }
    def functionExample() = {		    // Defining a function
          var a = 10
          a
    }
}

For more information: Click here.


9) What is the Function parameter with a default value in Scala?

Scala provides a feature to assign default values to function parameters. It helps in the scenario when you don't pass value during function calls. It uses default values of parameters.

Example

object MainObject {
   def main(args: Array[String]) = {
        var result1 = functionExample(15,2) 	// Calling with two values
        var result2 = functionExample(15)	// Calling with one value
        var result3 = functionExample()		// Calling without any value
        println(result1+"\n"+result2+"\n"+result3)
    }
    def functionExample(a:Int = 0, b:Int = 0):Int = {	// Parameters with default values as 0
        a+b
    }
}

For more information: Click here.


10) What is a function named parameter in Scala?

In Scala function, you can specify the names of parameters while calling the function. You can pass named parameters in any order and can also pass values only.

Example

object MainObject {
   def main(args: Array[String]) = {
        var result1 = functionExample(a = 15, b = 2)    // Parameters names are passed during call
        var result2 = functionExample(b = 15, a = 2)    // Parameters order have changed during call
        var result3 = functionExample(15,2)             // Only values are passed during call
        println(result1+"\n"+result2+"\n"+result3)
    }
    def functionExample(a:Int, b:Int):Int = {
        a+b
    }
}

For more information: Click here.


11) What is a higher order function in Scala?

Higher order function is a function that either takes a function as an argument or returns a function. In other words, we can say a function which works with function is called a higher-order function.

Example

object MainObject {
   def main(args: Array[String]) = {
     functionExample(25, multiplyBy2) 	 				// Passing a function as parameter
    }
    def functionExample(a:Int, f:Int=>AnyVal):Unit = {
        println(f(a))   								// Calling that function 
    }
    def multiplyBy2(a:Int):Int = {
        a*2
    }
}

For more information: Click here.


12) What is function composition in Scala?

In Scala, functions can be composed from other functions. It is a process of composing in which a function represents the application of two composed functions.

Example

object MainObject {
   def main(args: Array[String]) = {
     var result = multiplyBy2(add2(10))      // Function composition
     println(result)
    }
    def add2(a:Int):Int = {
        a+2
    }
    
    def multiplyBy2(a:Int):Int = {
        a*2
    }
}

For more information: Click here.


13) What is Anonymous (lambda) Function in Scala?

An anonymous function is a function that has no name but works as a function. It is good to create an anonymous function when you don't want to reuse it later. You can create anonymous function either by using ⇒ (rocket) or _ (underscore) wildcard in Scala.

Example

object MainObject {
   def main(args: Array[String]) = {
     var result1 = (a:Int, b:Int) => a+b        // Anonymous function by using => (rocket)
     var result2 = (_:Int)+(_:Int)              // Anonymous function by using _ (underscore) wild card
     println(result1(10,10))
     println(result2(10,10))
    }
}

For more information: Click here.


14) What is a multiline expression in Scala?

Expressions those are written in multiple lines are called multiline expression. In Scala, be careful while using multiline expressions.

Example

def add1(a:Int, b:Int) = {
        a
        +b
    }

The above program does not evaluate the complete expression and return b here.

For more information: Click here.


15) What is function currying in Scala?

In Scala, the method may have multiple parameter lists. When a method is called with a fewer number of parameter lists, this will yield a function taking the missing parameter lists as its arguments.

Example

object MainObject {
    def add(a:Int)(b:Int) = {
        a+b
    }
    def main(args: Array[String]) = {
        var result = add(10)(10)
        println("10 + 10 = "+result)
        var addIt = add(10)_
        var result2 = addIt(3)
        println("10 + 3 = "+result2)
    }
}

For more information: Click here.


16) What is a nexted function in Scala?

In Scala, you can define the function of variable length parameters. It allows you to pass any number of arguments at the time of calling the function.

Example

object MainObject {
    def add(a:Int, b:Int, c:Int) = {
        def add2(x:Int,y:Int) = {
            x+y
        }
        add2(a,add2(b,c))
    }
    def main(args: Array[String]) = {
        var result = add(10,10,10)
        println(result)
    }
}

For more information: Click here.


17) What is an object in Scala?

The object is a real-world entity. It contains state and behavior. Laptop, car, cell phone are the real world objects. An object typically has two characteristics:

1) State: data values of an object are known as its state.

2) Behavior: functionality that an object performs is known as its behavior.

The object in Scala is an instance of a class. It is also known as runtime entity.

For more information: Click here.


18) What is a class in Scala?

The class is a template or a blueprint. It is also known as a collection of objects of similar type.

In Scala, a class can contain:

  1. Data member
  2. Member method
  3. Constructor
  4. Block
  5. Nested class
  6. Superclass information, etc.

Example

class Student{
    var id:Int = 0;	        				// All fields must be initialized
    var name:String = null;
}
object MainObject{
    def main(args:Array[String]){
        var s = new Student()				// Creating an object
        println(s.id+" "+s.name);
    }
}

For more information: Click here.


19) What is an anonymous object in Scala?

In Scala, you can create an anonymous object. An object which has no reference name is called an anonymous object. It is good to create an anonymous object when you don't want to reuse it further.

Example

class Arithmetic{
    def add(a:Int, b:Int){
        var add = a+b;
        println("sum = "+add);
    }
}

object MainObject{
    def main(args:Array[String]){
        new Arithmetic().add(10,10);

    }
}

For more information: Click here.


20) What is a constructor in Scala?

In Scala, the constructor is not a special method. Scala provides primary and any number of auxiliary constructors. It is also known as default constructor.

In Scala, if you don't specify a primary constructor, the compiler creates a default primary constructor. All the statements of the class body treated as part of the constructor.

Scala Primary Constructor Example

class Student(id:Int, name:String){
    def showDetails(){
        println(id+" "+name);
    }
}

object MainObject{
    def main(args:Array[String]){
        var s = new Student(101,"Rama");
        s.showDetails()
    }
}

For more information: Click here.


21) What is method overloading in Scala?

Scala provides method overloading feature which allows us to define methods of the same name but having different parameters or data types. It helps to optimize code. You can achieve method overloading either by using different parameter list or different types of parameters.

Example

class Arithmetic{
    def add(a:Int, b:Int){
        var sum = a+b
        println(sum)
    }
    def add(a:Int, b:Int, c:Int){
        var sum = a+b+c
        println(sum)
    }
}

object MainObject{
    def main(args:Array[String]){
        var a  = new Arithmetic();
        a.add(10,10);
        a.add(10,10,10);
    }
}

For more information: Click here.


22) What is this in Scala?

In Scala, this is a keyword and used to refer a current object. You can call instance variables, methods, constructors by using this keyword.

Example

class ThisExample{
    var id:Int = 0
    var name: String = ""
    def this(id:Int, name:String){
        this()
        this.id = id
        this.name = name
    }
    def show(){
        println(id+" "+name)
    }
}

object MainObject{
    def main(args:Array[String]){
        var t = new ThisExample(101,"Martin")
        t.show()
    }
}

For more information: Click here.


23) What is Inheritance?

Inheritance is an object-oriented concept which is used to reusability of code. You can achieve inheritance by using extends keyword. To achieve inheritance, a class must extend to other class. A class which is extended called super or parent class. A class which extends class is called derived or base class.

Example

class Employee{
    var salary:Float = 10000
}

class Programmer extends Employee{
    var bonus:Int = 5000
    println("Salary = "+salary)
    println("Bonus = "+bonus)
}

object MainObject{
    def main(args:Array[String]){
        new Programmer()
    }
}

For more information: Click here.


24) What is method overriding in Scala?

When a subclass has the same name method as defined in the parent class, it is known as method overriding. When subclass wants to provide a specific implementation for the method defined in the parent class, it overrides a method from the parent class.

In Scala, you must use either override keyword or override annotation to override methods from the parent class.

Example

class Vehicle{
    def run(){
        println("vehicle is running")
    }
}

class Bike extends Vehicle{
     override def run(){
        println("Bike is running")
    }
}

object MainObject{
    def main(args:Array[String]){
        var b = new Bike()
        b.run()
    }
}

For more information: Click here.


25) What is final in Scala?

Final keyword in Scala is used to prevent inheritance of super class members into the derived class. You can declare the final variable, method, and class also.

Scala Final Variable Example

class Vehicle{
     final val speed:Int = 60
}
class Bike extends Vehicle{
   override val speed:Int = 100
    def show(){
        println(speed)
    }
}

object MainObject{
    def main(args:Array[String]){
        var b = new Bike()
        b.show()
    }
}

For more information: Click here.


26) What is the final class in Scala?

In Scala, you can create a final class by using the final keyword. A final class can't be inherited. If you make a class final, it can't be extended further.

Scala Final Class Example

final class Vehicle{
     def show(){
         println("vehicle is running")
     }

}

class Bike extends Vehicle{
       override def show(){
        println("bike is running")
    }
}

object MainObject{
    def main(args:Array[String]){
        var b = new Bike()
        b.show()
    }
}

For more information: Click here.


27) What is an abstract class in Scala?

A class which is declared with the abstract keyword is known as an abstract class. An abstract class can have abstract methods and non-abstract methods as well. An abstract class is used to achieve abstraction.

Example

abstract class Bike{
    def run()
}

class Hero extends Bike{
    def run(){
        println("running fine...")
    }
}

object MainObject{
    def main(args: Array[String]){
        var h = new Hero()
        h.run()
    }
}

For more information: Click here.


28) What is Scala Trait?

A trait is like an interface with partial implementation. In Scala, the trait is a collection of abstract and non-abstract methods. You can create a trait that can have all abstract methods or some abstract and some non-abstract methods.

Example

trait Printable{
    def print()
}

class A4 extends Printable{
    def print(){
        println("Hello")
    }
}

object MainObject{
    def main(args:Array[String]){
        var a = new A4()
        a.print()
    }
}

For more information: Click here.


29) What is a trait mixins in Scala?

In Scala, "trait mixins" means you can extend any number of traits with a class or abstract class. You can extend only traits or combination of traits and class or traits and abstract class.

It is necessary to maintain the order of mixins otherwise compiler throws an error.

Example

trait Print{
    def print()
}

abstract class PrintA4{
    def printA4()
}

class A6 extends PrintA4 {
    def print(){               				 // Trait print
        println("print sheet")
    }
    def printA4(){              				// Abstract class printA4
        println("Print A4 Sheet")
    }
}

object MainObject{
    def main(args:Array[String]){
        var a = new A6() with Print				// You can also extend trait during object creation
        a.print()
        a.printA4()
    }
}

For more information: Click here.


30) What is the access modifier in Scala?

Access modifier is used to define accessibility of data and our code to the outside world. You can apply accessibly to class, trait, data member, member method, and constructor, etc. Scala provides the least accessibility to access to all. You can apply any access modifier to your code according to your requirement.

In Scala, there are only three types of access modifiers.

  1. No modifier
  2. Protected
  3. Private

For more information: Click here


31) What is an array in Scala?

In Scala, the array is a combination of mutable values. It is an index based data structure. It starts from 0 index to n-1 where n is the length of the array.

Scala arrays can be generic. It means, you can have an Array[T], where T is a type parameter or abstract type. Scala arrays are compatible with Scala sequences - you can pass an Array[T] where a Seq[T] is required. Scala arrays also support all the sequence operations.

Example

class ArrayExample{
    var arr = Array(1,2,3,4,5)     	// Creating single dimensional array
    def show(){
        for(a<-arr)               		 // Traversing array elements
            println(a)
        println("Third Element  = "+ arr(2))        // Accessing elements by using index
    }
}

object MainObject{
    def main(args:Array[String]){
        var a = new ArrayExample()
        a.show()
    }
}

For more information: Click here.


32) What is an ofDim method in Scala?

Scala provides an ofDim method to create a multidimensional array. The multidimensional array is an array which stores data in matrix form. You can create from two dimensional to three, four and many more dimensional array according to your need.

Example

class ArrayExample{
    var arr = Array.ofDim[Int](2,2)  		 // Creating multidimensional array
    arr(1)(0) = 15                     		// Assigning value
    def show(){
        for(i<- 0 to 1){             		  // Traversing elements by using loop
           for(j<- 0 to 1){
                print(" "+arr(i)(j))
            }
            println()
        }
        println("Third Element = "+ arr(1)(1))        // Accessing elements by using index
    }
}

object MainObject{
    def main(args:Array[String]){
        var a = new ArrayExample()
        a.show()                     
    }
}

For more information: Click here.


33) What is String in Scala?

In Scala, the string is a combination of characters, or we can say it is a sequence of characters. It is index-based data structure and uses a linear approach to store data into memory. The string is immutable in Scala like java.

Example

class StringExample{
    var s1 = "Scala string example"
    def show(){
        println(s1)
    }
}

object MainObject{
    def main(args:Array[String]){
        var s = new StringExample()
        s.show()
    }
}

For more information: Click here.


34) What is string interpolation in Scala?

Starting in Scala 2.10.0, Scala offers a new mechanism to create strings from your data. It is called string interpolation. String interpolation allows users to embed variable references directly in processed string literals. Scala provides three string interpolation methods: s, f and raw.

Example

class StringExample{
    var pi = 3.14
    def show(){
        println(s"value of pi = $pi")
    }
}

object MainObject{
    def main(args:Array[String]){
        var s = new StringExample()
        s.show()
    }
}

For more information: Click here.


35) What does s method in Scala String interpolation?

The s method of string interpolation allows us to pass a variable in the string object. You don't need to use the + operator to format your output string. This variable is evaluated by the compiler and replaced by value.

Example

class StringExample{
    var s1 = "Scala string example"
    def show(){
        println(s"This is $s1")
    }
}

object MainObject{
    def main(args:Array[String]){
        var s = new StringExample()
        s.show()
    }
}

For more information: Click here.


36) What does f method in Scala String interpolation?

The f method is used to format your string output. It is like printf function of C language which is used to produce formatted output. You can pass your variables of any type in the print function.

Example

class StringExample{
    var s1 = "Scala string example"
    var version = 2.12
    def show(){
        println(f"This is $s1%s, scala version is $version%2.2f")
    }
}


object MainObject{
    def main(args:Array[String]){
        var s = new StringExample()
        s.show()
    }
}

For more information: Click here.


37) What does raw method in Scala String interpolation?

The raw method of string interpolation is used to produce a raw string. It does not interpret special char present in the string.

Example

class StringExample{
    var s1 = "Scala \tstring \nexample"    
    var s2 = raw"Scala \tstring \nexample"    
    def show(){
        println(s1)
        println(s2)
    }
}

object MainObject{
    def main(args:Array[String]){
        var s = new StringExample()
        s.show()
    }
}

For more information: Click here.


38) What is exception handling in Scala?

Exception handling is a mechanism which is used to handle abnormal conditions. You can also avoid termination of your program unexpectedly.

Scala makes "checked vs. unchecked" very simple. It doesn't have checked exceptions. All exceptions are unchecked in Scala, even SQLException, and IOException.

Example

class ExceptionExample{
    def divide(a:Int, b:Int) = {
            a/b				// Exception occurred here
        println("Rest of the code is executing...")
    }
}
object MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample()
        e.divide(100,0)
 
    }
}

For more information: Click here.


39) What is try catch in Scala?

Scala provides try and catch block to handle the exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in the try block. You can have any number of the try-catch block in your program according to need.

Example

In this example, we have two cases in our catch handler. The first case will handle only arithmetic type exception. The second case has a Throwable class which is a super-class in the exception hierarchy. The second case can handle any type of exception in your program. Sometimes when you don't know about the type of exception, you can use super-class.

class ExceptionExample{
    def divide(a:Int, b:Int) = {
        try{
            a/b
            var arr = Array(1,2)
            arr(10)
        }catch{
            case e: ArithmeticException => println(e)
            case ex: Throwable =>println("found a unknown exception"+ ex)
        }
        println("Rest of the code is executing...")
    }
}
object MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample()
        e.divide(100,10)
 
    }
}

For more information: Click here.


40) What is finally in Scala?

The finally block is used to release resources during exception. Resources may be a file, network connection, database connection, etc. The finally block executes guaranteed.

Example

class ExceptionExample{
    def divide(a:Int, b:Int) = {
        try{
            a/b
            var arr = Array(1,2)
            arr(10)
        }catch{
            case e: ArithmeticException => println(e)
            case ex: Exception =>println(ex)
            case th: Throwable=>println("found a unknown exception"+th)
        }
        finally{
            println("Finaly block always executes")
        }
        println("Rest of the code is executing...")
    }
}
object MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample()
        e.divide(100,10)
 
    }
}

For more information: Click here.


41) What is throw in Scala?

You can throw an exception explicitly in your code. Scala provides throw keyword to throw an exception. The throw keyword mainly used to throw a custom exception.

Example

class ExceptionExample2{
    def validate(age:Int)={
        if(age<18)
            throw new ArithmeticException("You are not eligible")
        else println("You are eligible")
    }
}

object MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample2()
        e.validate(10)
 
    }
}

For more information: Click here.


42) What is exception propagation in Scala?

In Scala, you can propagate the exception in calling chain. When an exception occurs in any function, it looks for the handler. If handler not available there, it forwards to caller method and looks for handler there. If handler presents there, handler catch that exception. If the handler does not present, it moves to next caller method in calling chain. This whole process is known as exception propagation.


43) What are throws in Scala?

Scala provides throws keyword for declaring the exception. You can declare an exception with method definition. It provides information to the caller function that this method may throw this exception. It helps to caller function to handle and enclose that code in a try-catch block to avoid abnormal termination of the program. In Scala, you can either use throws keyword or throws annotation to declare the exception.

Example

class ExceptionExample4{
    @throws(classOf[NumberFormatException])
    def validate()={
        "abc".toInt
    }
}

object MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample4()
        try{
            e.validate()
        }catch{
            case ex : NumberFormatException => println("Exception handeled here")
        }
        println("Rest of the code executing...")
    }
}

For more information: Click here.


44) What is a custom exception in Scala?

In Scala, you can create your exception. It is also known as custom exceptions. You must extend Exception class to while declaring custom exception class. You can create your message in custom class.

Example

class InvalidAgeException(s:String) extends Exception(s){}
class ExceptionExample{
    @throws(classOf[InvalidAgeException])
    def validate(age:Int){
        if(age<18){
            throw new InvalidAgeException("Not eligible")
        }else{
            println("You are eligible")
        }
    }
}
object MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample()
        try{
            e.validate(5)
        }catch{
            case e : Exception => println("Exception Occured : "+e)
        }
    }
}

For more information: Click here.


45) What is a collection in Scala?

Scala provides a rich set of collection library. It contains classes and traits to collect data. These collections can be mutable or immutable. You can use them according to your requirement.

For more information: Click here.


46) What is traversable in Scala collection?

It is a trait and used to traverse collection elements. It is a base trait for all Scala collections. It contains the methods which are common to all collections.

For more information: Click here.


47) What does Set in Scala collection?

It is used to store unique elements in the set. It does not maintain any order for storing elements. You can apply various operations on them. It is defined in the Scala.collection.immutable package.

Example

In this example, we have created a set. You can create an empty set also. Let's see how to create a set.

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        val set1 = Set()    						// An empty set
        val games = Set("Cricket","Football","Hocky","Golf") 	// Creating a set with elements
        println(set1)
        println(games)
    }
}

for more information: Click here.


48) What does SortedSet in Scala collection?

In Scala, SortedSet extends Set trait and provides sorted set elements. It is useful when you want sorted elements in the Set collection. You can sort integer values and string as well.

It is a trait, and you can apply all the methods defined in the traversable trait and Set trait.

Example

import scala.collection.immutable.SortedSet            
object MainObject{
    def main(args:Array[String]){
        var numbers: SortedSet[Int] = SortedSet(5,8,1,2,9,6,4,7,2)
        numbers.foreach((element:Int)=> println(element))
    }   
}

for more information: Click here.


49) What is HashSet in Scala collection?

HashSet is a sealed class. It extends AbstractSet and immutable Set trait. It uses hash code to store elements. It neither maintains insertion order nor sorts the elements.

Example

import scala.collection.immutable.HashSet
object MainObject{
    def main(args:Array[String]){
        var hashset = HashSet(4,2,8,0,6,3,45)
        hashset.foreach((element:Int) => println(element+" "))   
   }
}

For more information: Click here.


50) What is BitSet in Scala?

Bitsets are sets of non-negative integers which are represented as variable-size arrays of bits packed into 64-bit words. The largest number stored in it determines the memory footprint of a bitset. It extends Set trait.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var numbers = BitSet(1,5,8,6,9,0)
        numbers.foreach((element:Int) => println(element))
    }
}

For more information: Click here.


51) What is ListSet in Scala collection?

In Scala, ListSet class implements immutable sets using a list-based data structure. In ListSet class elements are stored internally in a reversed insertion order, which means the newest element is at the head of the list. This collection is suitable only for a small number of elements. It maintains insertion order.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var listset = ListSet(4,2,8,0,6,3,45)
        listset.foreach((element:Int) => println(element+" "))
    }
}

For more information: Click here.


52) What is Seq in Scala collection?

Seq is a trait which represents indexed sequences that are guaranteed immutable. You can access elements by using their indexes. It maintains insertion order of elements.

Sequences support many methods to find occurrences of elements or subsequences. It returns a list.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var seq:Seq[Int] = Seq(52,85,1,8,3,2,7)
        seq.foreach((element:Int) => print(element+" "))
        println("\nAccessing element by using index")
        println(seq(2))
    }
}

For more information: Click here.


53) What is Vector in Scala collection?

Vector is a general-purpose, immutable data structure. It provides random access of elements. It is suitable for a large collection of elements.

It extends an abstract class AbstractSeq and IndexedSeq trait.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var vector:Vector[Int] = Vector(5,8,3,6,9,4) //Or
        var vector2 = Vector(5,2,6,3)
        var vector3 = Vector.empty
        println(vector)
        println(vector2)
        println(vector3)
    }
}

For more information: Click here.


54) What is List in Scala Collection?

The List is used to store ordered elements. It extends LinearSeq trait. It is a class for immutable linked lists. This class is useful for last-in-first-out (LIFO), stack-like access patterns. It maintains order, can contain duplicates elements.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
       var list = List(1,8,5,6,9,58,23,15,4)
        var list2:List[Int] = List(1,8,5,6,9,58,23,15,4)
        println(list)
        println(list2)
    }
}

For more information: Click here.


55) What is the Queue in the Scala Collection?

Queue implements a data structure that allows inserting and retrieving elements in a first-in-first-out (FIFO) manner.

In Scala, Queue is implemented as a pair of lists. One is used to insert the elements and second to contain deleted elements. Elements are added to the first list and removed from the second list.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var queue = Queue(1,5,6,2,3,9,5,2,5)
        var queue2:Queue[Int] = Queue(1,5,6,2,3,9,5,2,5)
        println(queue)  
        println(queue2)
    }
}

For more information: Click here.


56) What is a stream in Scala?

The stream is a lazy list. It evaluates elements only when they are required. This is a feature of Scala. Scala supports lazy computation. It increases the performance of your program.

Example

object MainObject{
    def main(args:Array[String]){
        val stream = 100 #:: 200 #:: 85 #:: Stream.empty
        println(stream)
    }
}

For more information: Click here.


57) What does Map in Scala Collection?

The map is used to store elements. It stores elements in pairs of key and values. In Scala, you can create a map by using two ways either by using comma separated pairs or by using rocket operator.

Example

object MainObject{
    def main(args:Array[String]){
        var map = Map(("A","Apple"),("B","Ball"))
        var map2 = Map("A"->"Aple","B"->"Ball")
        var emptyMap:Map[String,String] = Map.empty[String,String] 
        println(map)
        println(map2)
        println("Empty Map: "+emptyMap)
    }
}

For more information: Click here.


58) What does ListMap in Scala?

This class implements immutable maps by using a list-based data structure. You can create empty ListMap either by calling its constructor or using ListMap.empty method. It maintains insertion order and returns ListMap. This collection is suitable for small elements.

Example

import scala.collection.immutable._
object MainObject{
    def main(args:Array[String]){
        var listMap = ListMap("Rice"->"100","Wheat"->"50","Gram"->"500")    // Creating listmap with elements
        var emptyListMap = new ListMap()            // Creating an empty list map
        var emptyListMap2 = ListMap.empty           // Creating an empty list map
        println(listMap)
        println(emptyListMap)
        println(emptyListMap2)
    }
}

For more information: Click here.


59) What is a tuple in Scala?

A tuple is a collection of elements in the ordered form. If there is no element present, it is called an empty tuple. You can use a tuple to store any data. You can store similar type of mixing type data. You can return multiple values by using a tuple in function.

Example

object MainObject{
    def main(args:Array[String]){
        var tuple = (1,5,8,6,4)     				// Tuple of integer values
        var tuple2 = ("Apple","Banana","Gavava")    	// Tuple of string values
        var tuple3 = (2.5,8.4,10.50)    			// Tuple of float values
        var tuple4 = (1,2.5,"India")    			// Tuple of mix type values
        println(tuple)
        println(tuple2)
        println(tuple3)
        println(tuple4)
    }
}

For more information: Click here.


60) What is a singleton object in Scala?

Singleton object is an object which is declared by using object keyword instead by class. No object is required to call methods declared inside a singleton object.

In Scala, there is no static concept. So Scala creates a singleton object to provide an entry point for your program execution.

Example

object Singleton{
    def main(args:Array[String]){
        SingletonObject.hello()         // No need to create object.
    }
}
object SingletonObject{
    def hello(){
        println("Hello, This is Singleton Object")
    }
}

For more information: Click here.


61) What is a companion object in Scala?

In Scala, when you have a class with the same name as a singleton object, it is called a companion class and the singleton object is called a companion object. The companion class and its companion object both must be defined in the same source file.

Example

class ComapanionClass{
    def hello(){
        println("Hello, this is Companion Class.")
    }
}
object CompanoinObject{
    def main(args:Array[String]){
        new ComapanionClass().hello()
        println("And this is Companion Object.")
    }
}

For more information: Click here.


62) What are case classes in Scala?

Scala case classes are just regular classes which are immutable by default and decomposable through pattern matching. It uses the equal method to compare instance structurally. It does not use the new keyword to instantiate the object.

Example

case class CaseClass(a:Int, b:Int)

object MainObject{
    def main(args:Array[String]){
        var c =  CaseClass(10,10)       // Creating object of case class
        println("a = "+c.a)               // Accessing elements of case class
        println("b = "+c.b)
    }
}

For more information: Click here.


63) What is file handling in Scala?

File handling is a mechanism for handling file operations. Scala provides predefined methods to deal with the file. You can create, open, write and read the file. Scala provides a complete package scala.io for file handling.

Example

import scala.io.Source
object MainObject{
  def main(args:Array[String]){
    val filename = "ScalaFile.txt"
    val fileSource = Source.fromFile(filename)
    for(line<-fileSource.getLines){
      println(line)
    }
    fileSource.close()
  }
}

For more information: Click here.



Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf