Dynamic Typing in Scala

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,

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,

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

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.

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.