Thursday, March 6, 2014

ScalaTips: Finding implicits applied from within eclipse

Scala is considered as a language easy to learn and hard to master. It can be a tad tricky to understand code written by a peer, even after acquiring an intermediate proficiency.

The Scala tips series of posts will focus on tips that will help our life as a developer simpler using tricks of trade. It will NOT focus on material for understanding the language itself.

Scala is a language suitable for development using ide, as is evident from the blossoming ecosystem of tools and plugins.

In this post we will take a quick look at how scala ide for eclipse assists in figuring out how implicit conversions has been applied.

Implicit conversions are particularly tricky bit when reading and understanding code. Implicit conversions allow automatic conversion from one type to another. So a piece of logic gets called without any visual indication of it being called.

Implicit conversions can be brought into scope by import statements. As we can have imports embedded in the code practically anywhere (package level, within class, object method, or code block) when using scala, we can have a number of disparate implicit conversions for the same type at work within a single eye span.

IDE to rescue!

Most of the modern IDEs will provide some visual indicator when implicit conversion is expected.

For example, by default the scala ide for eclipse will underline the expression, whose resultant value will be applied an implicit conversion.




In this code, "httpRequest.getHeaders(Names.CONNECTION)" is underlined. The getHeaders method returns a list of Strings. The return object is of the type java.util.List<String>

An implicit conversion is being applied here to wrap the list with a decorator "AsScala" which can then be used to convert the collection into a suitable collection from scala's own collection library -  scala.collection.mutable.Buffer[String].

There is an indicator on eclipse marker bar. On hovering on the marker, the details of the implicit conversion can be found.



Eclipse even provides us navigation to where the impiicit conversion is defined. Just take the cursor to the expression to which the implicit conversion is applied and press alt+F3

No comments:

Post a Comment