Know about Scala’s apply() function

scala_apply

In this blog post I will explain you one of the confusing feature of Scala for beginners i.e apply() method.

In Scala, classes can be constructed without using new keyword, like

val emp = Person()

The reason for this statement to create object is because of apply() function. Person() is not actually a constructor.

In Scala there are several ways to demo this:

val numbers = List(1,2,3,4,5)

In the above example also we are creating object of list without new keyword.

Apply Function Fundamentals

A easy way to use apply is to define it on a Object. Here’s an example:

object Greet {
    def apply(str : String) : String = {
        "M.r/ Mr.s"+str
    }
}

The apply function can be invoked using 2 ways:

  1. Invoking apply function explicitly
  2. Invoking apply function like a function

Invoking apply() function explicitly

// I can call apply explicitly if I want:
Greet.apply("John")

// Or I can call Greet like it is a function:
Greet("bob")

Invoking apply() function like a function

Greet("bob")

This is really done with some compile time sugar which translates function calls to Greet() into calls to Greet.apply(). So really the apply function is a simple short-hand that lets you save a few characters.

Different ways to use apply() function

Scala apply() function is used in several ways. Here are 4 interesting ways you can use the apply() function

Automatic Apply Functions for Case Class Companion Objects

Scala provides a special kind of class called the case class.Case classes provide you with an automatically generated apply function on their companion object that you can use like a constructor.

case class Employee(id : Integer, name: String, companyName: String)

The following three all do the same thing. Typically most developers use the first version

val e1 = new Employee(1, "Name-1", "Company-1") // normal constructor

val e2 = Employee(2, "Name-2", "Company-2") // this uses apply

val e3 = Employee.apply(3, "Name-3", "Company-3") // using apply manually

Apache Spark and Scala Training

Building a class using using apply()

In our previous example Greet.apply() returned a string, not an instance of a class called Greet. In this example we will return an object of another class.

class Company(name:String) {
  def fetchDetails(){
    println("Fetching details for: "+name)
  }
}

object Employee {
  def apply(id:Intname:String):Company = {
    println("Validating Employee: "id)
    new Company(name)
  }
}

Here’s a simple example:

abstract class DatabaseDriver {
  // some database stuff
}

object DatabaseDriver {
  def apply(config: Configuration) = config.dbType match {
    case "MYSQL" => new MySqlDriver()
    case "PSQL" => new PostgresDriver()
    case _ => new GenericDriver()
  }
}

// now I get the right version!
val mydatabase = DatabaseDriver(dbConfig)

 

Apply Functions are used for Anonymous Functions

val func = (x: String) => "hello %s".format(x)

// call the function
func("world")

The above code is actually creating an instance of a built in Function class i.e in this case Function1[String,String].

val func2 = new Function1[String, String] {
    def apply(x: String) = "hello %s".format(x)
}

// this works exactly the same:
func2("world")

Download code

Reference documentation


Learn Apache Spark by developing industry standard projects by following Agile methodologies  | Apache Spark Training with Project

 

Naveen P.N

12+ years of experience in IT with vast experience in executing complex projects using Java, Micro Services , Big Data and Cloud Platforms. I found NPN Training Pvt Ltd a India based startup to provide high quality training for IT professionals. I have trained more than 3000+ IT professionals and helped them to succeed in their career in different technologies. I am very passionate about Technology and Training. I have spent 12 years at Siemens, Yahoo, Amazon and Cisco, developing and managing technology.