Tag Archives: Scala

Dribbling about Scala Value Classes, Universal Traits and Extension methods

In this blog , I will share my working knowledge on Value Classes, Universal Traits and Extension methods of Scala.

Let’s start with the Value Classes of Scala. In this section we will talk about Value Classes Introduction, Use Case and it’s limitations.

Value classes have been around in Scala for a long time internally, and we have used them already many times because all Number’s in Scala use this compiler trick to avoid boxing and unboxing numeric values from int to scala.Int etc.

As a quick reminder, let’s recall that Array[Int] is an actual JVM int[] which has tons of performance implications, but in one word — arrays of numbers are fast, arrays of references not as much.

In more specific technical terms Value classes are a new mechanism in Scala to avoid allocating runtime objects. This is accomplished through the definition of new AnyVal subclasses. They were proposed in SIP-15.


Ok, since we now know the compiler has fancy tricks to avoid boxing ints into Ints when it doesn’t have to. Let’s see how this feature is exposed for us, end users since Scala 2.10.x. The feature is called “value classes”, is fairly simple to apply to your existing classes. Using them is as simple as adding extends AnyVal to your class and following a few rules listed bellow.

  • Value Class must have only a primary constructor with exactly one public, val parameter whose type is not a value class. (From Scala 2.11.0, the parameter may be non-public.)
  • Value Class may not have specialized type parameters.
  • Value Class may not have nested or local classes, traits, or objects
  • Value Class may not define a equals or hashCode method.
  • Value Class must be a top-level class or a member of a statically accessible object
  • Value Class can only have defs as members. In particular, it cannot have lazy vals, vars, or vals as members.
  • Value Class cannot be extended by another class.

Now we have enough descriptions about Value classes. Let’s go with a simple example of it. I will be using Case (Value) Classes in all my examples here, but it’s not technically required to do so. We can implement a Value Class using a normal class with one val parameter instead, but using case classes is usually the best way to go.

case class Hour(value: Double) extends AnyVal {
  def toMinute: Minute = Minute(value * 60)

case class Minute(value: Double) extends AnyVal {
  def toHour: Hour = Hour(value / 60)

Now we need to know about two important keywords related to Value Classes which is Universal Traits and Extension methods.

  • A universal trait is a trait that extends Any, only has def s as members, and does no initialization. Universal traits allow basic inheritance of methods for value classes, but they incur the overhead of allocation.
  • Extension methods serve the same purpose as Implicit conversions (which are a more general and more powerful utility), yet are better than conversions in one simple way — they avoid having to allocate the “Wrapper” object, which implicit conversions would otherwise use to provide the “added methods”. Extension methods take the route of rewriting the generated methods a little, so that they take the type-to-be-extended as their 1st argument.

These are the basics around Value Classes, Universal traits and Extension methods. If you want to read more about the different edge-cases around them, please refer to the official documentaion’s section about Value Classes where Mark Harrah, explains them very well with tons of examples, so I won’t be duplicating his effort here beyond the basic introduction 🙂 . As next step, I would look at how I can explain the use case of Value Classes and It’s functionality 🙂 Stay tuned.

FunHop: Working with Exceptions in Scala – Problem Statement


If you look at the earlier posts in the FunHop series, you would notice that Exceptions are side effects. Exceptions by their very nature also break referential transparency and are context dependent. You would have got an idea about referential transparency from our earlier post. If not, it might be a good idea to review it once.

Let us consider the code sequence below

What would happen when we call this method with fetchEmployeeName(-1) ?

It would throw the exception “Exception in thread “main” java.lang.Exception: Employee not found”

Now, let us apply Referential Transparency to the above code. The new avatar of the code becomes

What would be the output of fetchEmployeeName(-1) now? It would be “John”

Clearly exceptions are not referentially transparent. They are also context dependent. As you would notice in the above example, changing the context of the exception and bringing it inside the try…

View original post 300 more words

Continuous Integration : Integrating BuildKite with Your Scala Project

Integrating BuildKite with Your Scala Project


In a very broad sense, BuildKite (earlier called BuildBox) is a continuous integration server that allows you to keep working on your code while there is a CI box which is reporting about any issues. The problem with most web based CI servers is that they have to do a lot of magic beneath the hood to let you build your custom system on their environment.

What does this mean? This means that if your product uses the Riak database and mine uses PostgreSQL then a web based CI system would have to give me default installations of both of them so that both our products can be supported. Remember this is just 2 databases that we talked about. Now, bring in more databases, more external integration’s and to cap it, different versions of all of these for different products. Suddenly having a hosted CI is not really the space…

View original post 372 more words

Easiest Way To Map Optional Nested Case Class with Slick in Scala


Few days ago, I had a scenario, in which I was supposed to map optional nested case class in slick using Scala.

I was trying to do this mapping the way, I have explained below.

But I was getting below compilation error.

After beating my head two days, I found a solution by adding custom mapping.

It worked and now I am able to compile and run my code.

View original post

SBT-dependency tree


In this blog , I am going to describe how to view sbt dependency tree.  Last week I had a problem related to different cross version of a dependency. I knew the problem cause but  I had spent a day to know which dependency had brought that cross version of dependency. I did some study and browsing about that problem then I come across a sbt plugins as a potential solution of that problem.
In a project there is a chance of using same library but different version by multiple dependencies.  I also victim of dependency version conflict.  The good way is just draw a sbt dependency tree. Here is a sbt-plugin sbt-dependency graph is available for that.

Following are the steps to install and use sbt-dependency-graph
a) add plugin to project/plugins.sbt

b) add sbt setting in build.sbt

if project is multi module then add to Parent.scala:

Now run sbt…

View original post 14 more words

How to use Cookies in Play framework

Browser Cookies in Play framework


Play framework is being used by every Scala developer now a days. In this post we’ll learn about using Cookies in Play framework.

Play has a stateless architecture so in order to keep the data across multiple HTTP request we can use Session & Flash. But both Session & Flash loose data as soon as browser is closed. So, to retain data even after closing the browser, we can use Cookies in Play framework. Cookies are not stored by the server, instead they are stored at the client side.

  • Data stored in cookies are available till they expire or they are cleaned by user.
  • We can set the expiration time of cookies.
  • They can be made secure, but only for sites working on HTTPS.
  • They can be used like a Scala collection.

Before start using Cookies in Play framework these two libraries have to imported.

Storing the data in Cookie :

For the…

View original post 134 more words

Tutorial: AJAX calling in Play Framework 2.3.4

Cool AJAX integration with Play 2.3.4


In this tutorial we will discuss about the following topics of AJAX calling in Play Framework 2.3.4:

  1. Generating a Javascript router
    1. Embedded router
    2. Router resource
  2. Use of Javascript router
    1. jQuery Ajax
    2. Success/Error handler for each router
    3. Single Success/Error handler for all routers

View original post 478 more words