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,

  • selectDynamic – Allows to write field members e.g. employee.name
  • updateDynamic – Allows to write field updates e.g. employee.name = “Harsh”
  • applyDynamic – 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

About Harsh Sharma Khandal

Harsh is a Sr. Software Consultant at Knoldus Software LLP with 4 year of experience. He is a fan of programming standards and conventions. He has good knowledge of Scala, Java, 3D Modeling and 3D animation. His current passions include utilizing the power of Scala, Akka and Play to make reactive applications. He is a technologist and is never too far away from the keyboard. He believes in standard coding practices. His focus always remains on practical work. He has Master's in Computer Applications from Rajasthan Technical University, Kota. His hobbies include reading books and writing the code in multiple ways to find the best way it can be represented.
This entry was posted in Scala and tagged , , . Bookmark the permalink.

One Response to Dynamic Typing in Scala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s