By   June 16, 2015

Views / Implicit Conversions in Scala
Scala supports implicit conversion by providing the support for implicit methods. In this post we are going to discuss briefly about this feature. Let us first create a Scala SBT project. We are naming the project as ScalaImplicits.

Scala Implicit Conversion

Create Project

Let’s add a type Student. It is a case class with two properties. They are Id (int) and name (String).

Now let us provide an implementation of App. In the example below we are trying to instantiate a Student by assigning a string text to it. Off course, we cannot do that. We need to instantiate it by providing the values of id and name. Is this possible to just assign a string like this?

Building your code, would result in a compile time error. How can we still make it work?

compiler_error

Scala has an amazing implicit conversion feature. This is how it works. We need to provide a method definition using implicit keyword. In this method, we specify the details how such conversion should take place. Here in the example below, we are converting a text to Student object. The text is provided colon-separated in the format (id : name).

Now we just need to import the namespace with the object name wherever we need to use this conversion. This would help compiler figure out how to handle such conversion. Now the compiler should be happy!

implicit_import