Reading Time: 3 minutes

Scala provides different ways to share common data between the files. In a simplified way, a class is often used to share the values by storing them in methods in that class. But those methods are statically typed. What we mean by statically typed ?

Here we mean by statically typed, is that a class having a method declared and used everywhere we want to assign information and fetch from it. Now if there is a requirement to have a unique method every time we store some information in and fetch.

As Scala provides the dynamic typing, we have the following profits,

Code written in Scala will be more understandable due to well formed method names and arguments,

Dynamic typing will create the method at the execution time, we need not to type it statically,

Need not to create many variables, methods to store or calculate some common calculations with different purposes.

Case Study

In a class we describe behavior of a method that takes four arguments firstArg, secondArg, thirdArg and fourthArg. Now first two (firstArg,secondArg) are added and last two (thirdArg,fourthArg) are subtracted from it.

The behavior of dynamic methods creation can be stated as below,

Case 1: In this case we want to calculate the salary of the employee, now for this we create a dynamic method “calculateSalary”,

Case 2: In this case we want to calculate the difference of sum of two even numbers and odd numbers, now for this we create a dynamic method “differentiateEvenOdd”.

The dynamic typing allows us to call methods on objects that don’t exist or in other words it is a replica of “method missing” in dynamic languages. It doesn’t have any members, it is just a marker interface – the concrete implementation is filled-in by the compiler. To work with dynamic typing one can define four methods,

selectDynamic – Allows to write field members e.g. employee.name

– Allows to write field members e.g. employee.name updateDynamic – Allows to write field updates e.g. employee.name = “Harsh”

– Allows to write field updates e.g. employee.name = “Harsh” applyDynamic – Allows to call methods with arguments e.g. employee.name(firstName)

– Allows to call methods with arguments e.g. employee.name(firstName) applyDynamicNamed – Allows to call methods with named arguments e.g. employee.name(firstName = “Harsh”, lastName = “Khandal”)

Now to use any one of these methods it is enough to write a class that extends Dynamic and to implements the methods there.

First of all we need to include a package to set the language option to dynamic,

import scala.language.dynamics

Now we create a class that extends the Dynamic interface and start writing the definition for methods there,

class Calculator extends Dynamic { // method implementations here }

selectDynamic

It is the easiest of all four methods. In this the compiler translates a call of employee.name to employee.selectDynamic(“name”), thus it is required that this method has an argument list expecting a String.

class Calculator extends Dynamic { def selectDynamic(name: String) = name }

scala> val calc = Calculator

calc: Calculator = Calculator@6040af64

scala> calc.salary

res37: String = salary

scala> calc.bonus

res38: String = bonus

scala> calc.selectDynamic(“calc”)

res54: String = calc

updateDynamic

It is used to update a value. The name of the field to update and its value are passed to different argument lists by the compiler.

class Calculator extends Dynamic { var map = Map.empty[String, Int] def selectDynamic(name: String) = { map get name getOrElse sys.error("Method not initialized yet") } def updateDynamic(name: String)(amount: Int) { map += name -> amount } }

scala> val calc = Calculator

calc: Calculator = Calculator@6040af64

scala> calc.salary

java.lang.RuntimeException: Method not initialized yet

scala> calc.salary = 5000

calc.salary: Int = 5000

scala> calc.salary

res 48: Int = 5000

Note: updateDynamic always needs to be implemented with selectDynamic otherwise we get a compile time error.

applyDynamic

Now if the requirement is to pass the argument in method, then applyDynamic comes in use,

class Calculator extends Dynamic { def applyDynamic(name: String)(fstNum: Int, secNum: Int, thrNum: Int, fthNum: Int) = { (fstNum + secNum - thrNum - fthNum) } }

scala> val calc = new Calculator

calc: Calculator = Calculator@19ae6bb

scala> calc.calculateSalary(5000, 2000, 400, 500)

res3: Int = 6100

scala> calc.differentiateEvenOdd(20, 80, 15, 35)

res4: Int = 50

applyDynamicNamed

This method is similar to applyDynamic method except the parameter names, so if we need to name our parameter names then we can use it,

class Calculator extends Dynamic { def applyDynamicNamed(name: String)(args: (String, Int)*) = { args map { argument => val (name, value) = argument println(name+ " is "+value) } s"${args.length} arguments have been received" } }

scala> val cal = new Calculator

cal: Calculator = Calculator@68f6e55d

scala> cal.showDetails(salary = 50000, hra = 2000)

salary is 50000

hra is 2000

res14: String = 2 arguments have been received

So this is the way how we can use dynamic typing in Scala.

thanks