Some Important Features of Scala

Reading Time: 3 minutes

Scala is a programming language that supports both functional programming and object-oriented programming. It has powerful features. Scala language is based on java language so if you are aware of java it is easy to learn Scala

Features of Scala

  • Type inference
  • Singleton object
  • Immutability
  • Lazy evaluations
  • Case classes and Pattern matching
  • String interpolation
  • Higher order function
  • Trait
  • Rich collection set

Type Inference

There is no need to mention the return type of function and data type explicitly because scala can automatically deduce the type of data. In Functions, the type of the last expression would be the return type of function.

val num = 123
println(num.getClass)

val string= "Scala"
println(string.getClass)

Output :

int

class java.lang.String

Singleton Object

In Scala, There is no static key concept (variable and methods). Scala creates a singleton object to provide entry point for your program. Singleton object is declared by using object keyword and there is no need to create object to call methods inside singleton object.

Syntax :

object Name{
// code...
}

Immutability

In Scala, Each variable is immutable by default. Immutable means you can’t change the value but if you want mutable variable you can also create mutable variable which can be change

Example :

scala> val num = 123
num: Int = 123

scala> num = 321
<console>:12: error: reassignment to val
       num = 321

If we are changing the value of num, we’d get a compilation error.

If you want to have change value. You need to use a mutable variable declare by using var keyword:

Example :

scala> var num =123
num: Int = 123

scala> num =321
num: Int = 321

scala> assert(num == 321)

Lazy Evaluations

Evaluation is lazy by default in Scala. Scala evaluates expression only when they are required, and you can also declare a lazy variable by using lazy keyword. It is used to increase performance.

Example :

scala> val list = List(1,2,3)
list: List[Int] = List(1, 2, 3)

scala> lazy val squareOfList = list.map(x => x*x) 
squareOfList: List[Int] = <lazy>

scala> println(squareOfList)
List(1, 4, 9)

Case classes and Pattern matching

Case classes are like regular classes that have default apply() method which handle object construction. There is no  need to use a new keyword to create an object.

Case class provides purely functional code with immutable objects. Case classes are a representation of a data structure with the necessary methods. It support pattern matching.

Example :

trait Employee
case class Intern(name: String) extends Employee
case class SoftwareConsultant(name: String) extends Employee
case class SeniorSoftwareConsultant(name: String) extends Employee

object Main extends App {
  def getEmployee(employee: Employee): String = {
    employee match {
      case Intern(name) => s"Hello, My name is $name and  I am Intern"
      case SoftwareConsultant(name) => s"Hello, My name is $name and  I am Software Consultant"
      case SeniorSoftwareConsultant(name) => s"Hello, My name is $name and  I am Senior Software Consultant"
    }
  }
}

String Interpolation

This was introduced in Scala 2.10. There are three types of Sting interpolation s, f, and raw. String interpolation allows the evaluation of a literal string containing placeholders

s String Interpolation

val sStringInterpolation = "Scala"
println(s"Welcome to $sStringInterpolation")

Output:

Welcome to Scala

f String Interpolation

val height = 1.9
val name = "Harsh"
println(f"$name%s is $height%2.2f meters tall")

Output :

Harsh is 1.90 meters tall

raw String Interpolation

println(raw"Welcome to Scala \nMy name is Harsh")

Output :

Welcome to Scala \nMy name is Harsh

Higher Order Function

Scala provides feature of higher-order function. It is a function that takes another function as an argument and returns a function as a result

Example :

 def SquareOfNum(num:Int,square:Int => Int):Int =square(num)
 def Square(num:Int):Int=num*num
 println(SquareOfNum(4,Square))

Trait

Scala provides concept of traits. It is similar to an interface with a partial implementation. A trait is used to share interfaces and fields between classes. You can create traits by using trait keywords that can have abstract methods and some non-abstract methods.

Example :

trait PrintSomething {
    def print(): Unit
  }

class TraitExample extends PrintSomething {
    override def print(): Unit = println("Welcome to Scala")
  }

Rich collection set

Scala has a rich collection library and is located in the scala collection package. Scala collection has mutable and immutable types. Collections are like containers and containers can be sequenced, linear sets of items for example:- List, Tuple, Option, Map, etc.

Scala Immutable Collections Hierarchy

Conclusion

Through this blog, You will get the basic knowledge about Scala Features and also it provides us with a more concise and readable code. We explored the Scala Features like Immutability, case class, pattern matching, etc.

Written by 

Vineet Chauhan is a Software Consultant Intern at Knoldus Inc. His practice area is Scala. He is a good team worker. He is always ready to face any challenging task.

1 thought on “Some Important Features of Scala4 min read

Leave a Reply

%d bloggers like this: