Scala: Handy implicit

Niroj Pattnaik
2 min readNov 20, 2020

Whenever I get a chance to work in Scala, I always love its simplicity like Python, handiness like Perl, and running like Java.

Scala’s implicit ways are another way of writing syntactical sugary flavors of writing compact code in your own style which makes it easier to call from external class or code blocks. Here, I’m keeping a few custom definitions I use frequently:

I. CamelCase :

A camel case implicit function can be handy while storing strings like First & Last Name. It can be also easily called from Spark using a UDF as shown below:

scala> "niroj pattnaik".toCamelCase
val res21: String = Niroj Pattnaik
scala> "niroj K pattnaik".toCamelCase
val res22: String = Niroj K Pattnaik

II. Database Result Conversion:

Calling a DB resultset object from an external class not only looks ugly but also keeps the responsibility on the user to loop through the result set and do the conversions. Here I’m trying to help the fellow users to call it externally in an easier way:

val colValue = ExecuteDbQuery.as[Long](configFilePath = "db2.config", query = s"SELECT col FROM TABLE"                                      )(0)(0)val result = ExecuteDbQuery.as[Any](configFilePath = "db2.config",                                      query = s"SELECT col1,col2 FROM TABLE"                                      )
val col1Value = result(0)(0).parse(Long)
val col2Value = result(0)(1).parse(Int)

III. Easy Sequence Differentiations:

Here I’m overriding the minus(“-”) sign to find an iterable object like a Sequence object. The data type is kept generic type [A] here:

scala> Seq("A", "B") - Seq("A")
val res24: Seq[String] = List(B)
scala> Seq(1, "B") - Seq("A")
val res25: Seq[Any] = List(1, B)

Hope you like it. Implicit function makes the Scala code more readable like shown in the above few examples. I will keep on adding such new implicit functions whenever time permits in these sections.

Thank you for reading. Please like and comment if you find it helpful.

--

--

Niroj Pattnaik

Hadoop Developer |BigData/ETL Engineer| Techincal Architect| And a Student.