Scala – Tips & Tricks

1. Companion Object :

If the object & a class share the same name & are located in same source file, they are called companion.

A companion class can access private method & fields inside of it’s companion object & vice versa

companion object can be use to implement various design pattern like factory design pattern , singleton design pattern

companion object works same way the static method works in java


2. Case class & Case Object :

Data class represents data types in domain , Imagine an online store where customer, Account,order,Inventory are all types of domain

Service class represents works to be performed in an application. They know what to do but they donot hold data themselves , When application calls the service they pass data to service, and service transform it in some other way, Example : Persistance ,  Logger , Calculation engine.

Case class is a representation of data types that removes a lots of boilerplate code , it generates JVM specific convinient  method, Makes every class parameter a field, is immutable by default hence thread safe , perform value-based equivalence by default.

3. Higher Order functions :

As scala is functional programming , it supports higher order function where function can take an argument as another function whose(the function as argument) declaration(calling part) is written inside function’s definition & it’s implementation is defined during either declaration of outer function in the form of anonymous function or directly declaring as any other function & calling it.

object higherOrder {

def applyF(i:Int,f:(Int)=>Int) {

def multiply(x:Int):Int = {

def main(args:Array[String])  {