17: Coding Scala Way – What is wrong with this code?

Q. What is wrong with the below code? How will you fix it?

A. The above code will always return “false”. Why? Because map.get(id) returns Some(2016), which is not == to the String value of “2016”. The “==” is not a type safe equal, hence won’t give you a compile error. If you look at the Scala API for Map, you will see

Scala Map API

Scala Map API

Fix #1: Using implicits

Using implicits as shown below by defining a type safe === method as shown below.

Output:

The compiler rewrites the below code with implicits as

As

where === is an instance method of class Equal. You can also use a map() function as shown below:

Which the compiler rewrites with implicits as:

The Scala’s syntactic sugar allows it to be written as:

Fix #2: Scalaz library ===

Add the Scalaz library via Maven or sbt.

and then

Fix #3: Cats library ===

Add the Cats library via Maven or sbt.

and then

Scalaz and Cats are libraries which provide Functional Programming constructs for Scala.


300+ Java & Big Data Interview FAQs

16+ Java Key Areas Interview Q&As

800+ Java Interview Q&As

300+ Java & Big Data Tutorials

Top