<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Functional Programming etc.</title>
    <description>Posts about Scala etc.
</description>
    <link>http://aakashns.github.io/</link>
    <atom:link href="http://aakashns.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Sat, 28 May 2016 22:17:41 +0000</pubDate>
    <lastBuildDate>Sat, 28 May 2016 22:17:41 +0000</lastBuildDate>
    <generator>Jekyll v3.1.6</generator>
    
      <item>
        <title>Simple Typed Maps</title>
        <description>&lt;p&gt;If you’ve ever wanted to store and access values of different types using an ordinary &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt;, here’s what you need :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/2d4c3076f7d423d57e40.js?file=typedMap.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;It’s just 20 lines of code, with no dependencies. You can drop it into your project and start using it right away. Don’t worry if the code doesn’t make sense, we’ll go over the implementation in detail later. But let’s try it out first, starting with a &lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt; (you might want to follow along in a REPL of your own) :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=import.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;In the key &lt;code class=&quot;highlighter-rouge&quot;&gt;k1&lt;/code&gt;, apart from the string &lt;code class=&quot;highlighter-rouge&quot;&gt;&quot;a&quot;&lt;/code&gt;, we’re also storing information about the type of value it will point to in the &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; using a &lt;code class=&quot;highlighter-rouge&quot;&gt;TypeTag&lt;/code&gt;. You can learn about &lt;code class=&quot;highlighter-rouge&quot;&gt;TypeTag&lt;/code&gt;s and type erasure &lt;a href=&quot;http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html&quot;&gt;here&lt;/a&gt;, but the basic idea is that they let you work with types at runtime.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt; is a simple case class, except that the &lt;code class=&quot;highlighter-rouge&quot;&gt;equals&lt;/code&gt; method is overridden to compare the underlying key as well as the value type correctly (you can’t compare &lt;code class=&quot;highlighter-rouge&quot;&gt;TypeTag&lt;/code&gt;s using &lt;code class=&quot;highlighter-rouge&quot;&gt;==&lt;/code&gt;). Let’s try to create a &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; using &lt;code class=&quot;highlighter-rouge&quot;&gt;k1&lt;/code&gt; :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=pairOperator.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;Surprise! It doesn’t compile. Why is that? Well, the &lt;code class=&quot;highlighter-rouge&quot;&gt;-&amp;gt;&lt;/code&gt; operator in scala is not a primitive. It is implemented by means of an &lt;a href=&quot;https://github.com/scala/scala/blob/v2.11.6/src/library/scala/Predef.scala#L247&quot;&gt;implicit class&lt;/a&gt;, and creates a &lt;code class=&quot;highlighter-rouge&quot;&gt;Tuple2&lt;/code&gt; of the arguments around it. We would like to exercise some control over the type of values a &lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt; can be paired with, so we have &lt;em&gt;disabled&lt;/em&gt; the implicit &lt;code class=&quot;highlighter-rouge&quot;&gt;-&amp;gt;&lt;/code&gt; operator by defining it as a method on &lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt;. This method returns &lt;code class=&quot;highlighter-rouge&quot;&gt;None&lt;/code&gt;, which cannot be provided as a constructor argument to &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To pair a &lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt; with a value, we shall use the type safe arrow method &lt;code class=&quot;highlighter-rouge&quot;&gt;~&amp;gt;&lt;/code&gt; :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=tildaFail.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;Since &lt;code class=&quot;highlighter-rouge&quot;&gt;k1&lt;/code&gt; is of type &lt;code class=&quot;highlighter-rouge&quot;&gt;Key[String, Int]&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;~&amp;gt;&lt;/code&gt; expects an &lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt;, and compilation fails if we try to give it anything else. Let’s create a valid &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; and try to access the value stored in it :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=tildaCreate.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;We were able ensure that &lt;code class=&quot;highlighter-rouge&quot;&gt;k1&lt;/code&gt; points an &lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt; value, but when we try to access it, we get back a value of type &lt;code class=&quot;highlighter-rouge&quot;&gt;Any&lt;/code&gt;, which is no good! Let’s fix this using &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;, which is a wrapper around &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; that lets you get back values with the right types :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=typedMapCreated.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;Voila! The value we get out of the map &lt;code class=&quot;highlighter-rouge&quot;&gt;m&lt;/code&gt; using &lt;code class=&quot;highlighter-rouge&quot;&gt;k1&lt;/code&gt; magically has the right type (we’re casting it under the hood, but let’s keep that between us). Here’s a map with different types of values :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=typedMapMultiple.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;We can recover each of the values with the right type using just the keys :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=typedMapMultipleUsed.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;And we can work with keys that aren’t present in the map just as easily :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=typedMapMultipleAbsent.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;At this point, you might want to scroll back up all the way and go through the implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;, and it should make a lot more sense. Now you can use a &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; just like you would a &lt;a href=&quot;http://docs.scala-lang.org/tutorials/tour/case-classes.html&quot;&gt;case class&lt;/a&gt; or a tuple. Or you could just use a case class, right? Well, case classes and tuples are great, except when they’re a huge pain the ass. Specifically :&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Tuple elements have to be accessed as &lt;code class=&quot;highlighter-rouge&quot;&gt;._1&lt;/code&gt; , &lt;code class=&quot;highlighter-rouge&quot;&gt;._2&lt;/code&gt; etc., which is just plain ugly. Case classes solve this by letting you name the elements. &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;s let you use pretty much anything as a key, and you can decide which ones to use at runtime.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;You cannot build a tuple or a case class in steps, you have to build it all in one go. You might wrap the elements in &lt;code class=&quot;highlighter-rouge&quot;&gt;Option&lt;/code&gt;s, but then you find yourself calling &lt;code class=&quot;highlighter-rouge&quot;&gt;.get&lt;/code&gt; (or pattern matching) all over the place. &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;s can be built in steps by adding key-value pairs one by one.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Case classes and tuples are unbelievably rigid, to the point that it is annoying. They don’t compose at all! You can’t concatenate tuples, and if you want to combine case classes you will have to write a ton of boilerplate to do it. &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;s are ordinary &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt;s, so you can combine them quite easily.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Sometimes you need a traditional &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; i.e. a set of key-value pairs, with keys and values that can be passed around independently and used across multiple maps. A case class is simply too restrictive in such situations.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;While &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Key&lt;/code&gt; are good to use as defined above, there’s bit of boilerplate involved in using them. Let’s define some helper classes to help clean up the syntax :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/2d4c3076f7d423d57e40.js?file=TypedMapSyntax.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;With the help of these implicit classes, it becomes much easier to create and use &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;s :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/1b840ca405d9cfa0a87d.js?file=typedMapPretty.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;That’s pretty much it! Feel free to use it, but keep in mind that this is a simple (albeit functional) implementation and has several shortcomings. For instance, you can ask for a key that doesn’t exist and it will blow up at runtime, like an ordinary &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; would. Also, since you have access to the underlying &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt;, you can call methods like &lt;code class=&quot;highlighter-rouge&quot;&gt;.map&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;.flatMap&lt;/code&gt; etc. on it and totally mess up the whole thing and get all kinds of runtime exceptions. This can be avoided by making the underlying &lt;code class=&quot;highlighter-rouge&quot;&gt;Map&lt;/code&gt; private and exposing only a limited set of methods on &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;. If you need better compile time safety and more features, you should check out &lt;a href=&quot;https://github.com/scala-records/scala-records&quot;&gt;scala records&lt;/a&gt; or &lt;a href=&quot;https://github.com/milessabin/shapeless/blob/master/examples/src/main/scala/shapeless/examples/records.scala&quot;&gt;shapeless records&lt;/a&gt;. I would suggest that you use case classes whenever you can, but when you find that your head hurts trying to do what you want, use &lt;code class=&quot;highlighter-rouge&quot;&gt;TypedMap&lt;/code&gt;s (or something similar). Here’s the full implementation (&lt;a href=&quot;https://gist.githubusercontent.com/aakashns/2d4c3076f7d423d57e40/raw/5ae7c25a64d3bb941b163786913abd5a3e9e08f1/typedMapFull.scala&quot;&gt;raw&lt;/a&gt;) :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/2d4c3076f7d423d57e40.js?file=typedMapFull.scala&quot;&gt; &lt;/script&gt;

</description>
        <pubDate>Tue, 16 Jun 2015 04:10:00 +0000</pubDate>
        <link>http://aakashns.github.io/typed-map.html</link>
        <guid isPermaLink="true">http://aakashns.github.io/typed-map.html</guid>
        
        
        <category>scala</category>
        
      </item>
    
      <item>
        <title>Scrap Your Type Class Boilerplate (2/2)</title>
        <description>&lt;p&gt;For the &lt;strong&gt;TL; DR&lt;/strong&gt; version, go straight to the &lt;a href=&quot;#summary&quot;&gt;Summary&lt;/a&gt;.&lt;/p&gt;

&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#recap&quot; id=&quot;markdown-toc-recap&quot;&gt;Recap&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#more-improvements&quot; id=&quot;markdown-toc-more-improvements&quot;&gt;More Improvements&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#helper-class&quot; id=&quot;markdown-toc-helper-class&quot;&gt;Helper Class&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#the-typeclasscompanion-trait&quot; id=&quot;markdown-toc-the-typeclasscompanion-trait&quot;&gt;The TypeClassCompanion Trait&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#implicit-class-for-pretty-syntax-or-not&quot; id=&quot;markdown-toc-implicit-class-for-pretty-syntax-or-not&quot;&gt;Implicit Class for Pretty Syntax (or not)&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#summary&quot; id=&quot;markdown-toc-summary&quot;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;recap&quot;&gt;Recap&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;/better-type-class.html&quot;&gt;previous post&lt;/a&gt; covered some ways to make type classes easier to use. For a quick recap, see the &lt;a href=&quot;/better-type-class.html#summary&quot;&gt;summary&lt;/a&gt;. In this post, we will attempt to eliminate some of the boilerplate associated with creating and using type classes and their instances. Here is the implementation of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; type class that we had at the end of the previous post :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/a69d8e602c3093356b7c.js?file=Group.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;Inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; companion object, we define instances of &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; for &lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt; and pairs :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/a69d8e602c3093356b7c.js?file=GroupInstances.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;And here, the type class is used to define some generic functions :
&lt;script src=&quot;https://gist.github.com/aakashns/a69d8e602c3093356b7c.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;h2 id=&quot;more-improvements&quot;&gt;More Improvements&lt;/h2&gt;

&lt;p&gt;One of the concerns raised earlier but not addressed was that the code for defining type class instances is rather verbose and repetitive, and if the type class has lots of abstract methods or if you’re defining many instances, this can lead to a lot of boilerplate. I alluded to something called &lt;em&gt;the pain of overriding&lt;/em&gt;, which is the root of much of this boilerplate. Here is the definition &lt;s&gt;from Wikipedia&lt;/s&gt; :&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet tw-align-center&quot; lang=&quot;en&quot;&gt;&lt;p&gt;The pain of overriding : The &lt;a href=&quot;https://twitter.com/hashtag/Scala?src=hash&quot;&gt;#Scala&lt;/a&gt; compiler can infer batshit crazy types, still demands the full signature to override/implement methods.&lt;/p&gt;&amp;mdash; Aakash N S (@aakashns) &lt;a href=&quot;https://twitter.com/aakashns/status/584373978849943552&quot;&gt;April 4, 2015&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;It is annoying to write all these types, and it becomes much more annoying when you have to change something, because you have to make the same change in &lt;em&gt;SO&lt;/em&gt; many places, and so you end up copy-pasting things all over the place, but that leaves you with a bunch of compilation errors, and then you spend a day figuring out the types to fix those errors, and then you finally fix them, and you reward yourself with a cookie or whatever, but then two days later you realize you’ve made an error in the logic because you were too busy trying to tell the compiler what it already knows!&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://media.tumblr.com/tumblr_mcl3yteMCb1rw8654.gif&quot; alt=&quot;All those types!&quot; class=&quot;center-image responsive-image&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;helper-class&quot;&gt;Helper Class&lt;/h3&gt;

&lt;p&gt;To help eliminate some of this boilerplate, let’s define a class &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupAux&lt;/code&gt; as follows :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/c33c8cdd4b2d63bab60a.js?file=GroupAux.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;This class does nothing special. It simply moves the methods to be implemented into constructor arguments. Using this helper class, the code for defining instances of &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; for &lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt; looks like this :
&lt;script src=&quot;https://gist.github.com/aakashns/c33c8cdd4b2d63bab60a.js?file=IntGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Isn’t this much nicer? By using anonymous functions as constructor arguments to &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupAux&lt;/code&gt;, we’re letting the compiler do all the hard work of figuring out the right types. By the way, anonymous functions are also called lambdas (λ). And here’s the definition for &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup&lt;/code&gt; :
&lt;script src=&quot;https://gist.github.com/aakashns/c33c8cdd4b2d63bab60a.js?file=pairGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;You can make the anonymous functions more descriptive, &lt;a href=&quot;https://www.youtube.com/watch?v=vgUHqk-4omc&quot;&gt;if you’re not into the whole brevity thing&lt;/a&gt; :
&lt;script src=&quot;https://gist.github.com/aakashns/c33c8cdd4b2d63bab60a.js?file=GroupInstancesLong.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Admittedly, this is not a huge improvement if you only have a few instances of the type class. Some people would argue that this not an improvement at all, because it compromises on readability. Here are a few arguments in favor of this style :&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;It avoids the &lt;em&gt;pain of overriding&lt;/em&gt;. You no longer have to tell the compiler what it can figure out on its own. If the instances of your type class go into dozens, or if you have many abstract methods to be implemented, this can save you the trouble of having to write all the types all the time.&lt;/li&gt;
  &lt;li&gt;Anonymous functions are not unreadable if you already know the types. That’s precisely why we use them. When both the reader and the compiler already know the types, they’re just noise in the code. Moreover, you can optionally provide the types, if you &lt;em&gt;really&lt;/em&gt; want to.&lt;/li&gt;
  &lt;li&gt;It’s not all or nothing. You don’t have to use it all the time. Use it when it saves you precious lines without compromising on readability, like in the case of &lt;code class=&quot;highlighter-rouge&quot;&gt;IntGroup&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;DoubleGroup&lt;/code&gt;. If you think the definition of &lt;code class=&quot;highlighter-rouge&quot;&gt;PairGroup&lt;/code&gt; feels unreadable, don’t use &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupAux&lt;/code&gt;! Extend &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; and override the methods directly.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Note that this is a general technique that you can apply to any trait / abstract class. Just define a helper class that takes function values as constructor arguments, and uses them to implement the abstract methods.&lt;/p&gt;

&lt;h3 id=&quot;the-typeclasscompanion-trait&quot;&gt;The TypeClassCompanion Trait&lt;/h3&gt;

&lt;p&gt;This is another minor improvement, that can help you avoid having to write the &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method for your type class companion object. We define a trait called &lt;code class=&quot;highlighter-rouge&quot;&gt;TypeClassCompanion&lt;/code&gt; that companion objects can extend, to automatically get the &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method :
&lt;script src=&quot;https://gist.github.com/aakashns/340068446e3fd59196be.js?file=TypeClassCompanion.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Note that the apply method is marked as &lt;code class=&quot;highlighter-rouge&quot;&gt;@inline&lt;/code&gt;, which tells the compiler to replace calls like &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[Int]&lt;/code&gt; with &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly[Group[Int]]&lt;/code&gt;. Not surprisingly, the implicitly method in Predef is &lt;a href=&quot;https://github.com/scala/scala/blob/v2.11.6/src/library/scala/Predef.scala#L130&quot;&gt;inlined by the complier&lt;/a&gt; too, so the compiler will replace &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly[Group[Int]]&lt;/code&gt; with an implicit value of type &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[Int]&lt;/code&gt; &lt;em&gt;summoned from the nether world&lt;/em&gt;. Long story short, the compiler will replace the expression &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[Int]&lt;/code&gt; with &lt;code class=&quot;highlighter-rouge&quot;&gt;IntGroup&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Using the &lt;code class=&quot;highlighter-rouge&quot;&gt;TypeClassCompanion&lt;/code&gt; trait, the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; companion object looks like this :
&lt;script src=&quot;https://gist.github.com/aakashns/340068446e3fd59196be.js?file=Group.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;There isn’t much more to it than that. It saves you one line of code for each of your type classes.&lt;/p&gt;

&lt;h3 id=&quot;implicit-class-for-pretty-syntax-or-not&quot;&gt;Implicit Class for Pretty Syntax (or not)&lt;/h3&gt;

&lt;p&gt;With context bounds and the &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method on the companion object, the syntax for using type classes is already pretty clean. However, it is often the case that the methods defined in the type class are unary (a function of type &lt;code class=&quot;highlighter-rouge&quot;&gt;T =&amp;gt; T&lt;/code&gt;) or binary (a function of type &lt;code class=&quot;highlighter-rouge&quot;&gt;(T, T) =&amp;gt; T&lt;/code&gt;) operations. This is certainly true for &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; : &lt;code class=&quot;highlighter-rouge&quot;&gt;plus&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;minus&lt;/code&gt; are binary operations, and &lt;code class=&quot;highlighter-rouge&quot;&gt;inverse&lt;/code&gt; is a unary operation. Wouldn’t it be nice if we could simply write &lt;code class=&quot;highlighter-rouge&quot;&gt;(1, 2) + (3, 4)&lt;/code&gt; instead of &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[(Int, Int)].plus((1, 2), (3, 4))&lt;/code&gt;? Here’s some advice I just made up :&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet tw-align-center&quot; lang=&quot;en&quot;&gt;&lt;p&gt;As a rule of thumb, the answer to every question of the form “Can I do XYZ in &lt;a href=&quot;https://twitter.com/hashtag/Scala?src=hash&quot;&gt;#Scala&lt;/a&gt;?” is “Yeah, totally man! Just use implicits.”&lt;/p&gt;&amp;mdash; Aakash N S (@aakashns) &lt;a href=&quot;https://twitter.com/aakashns/status/587687158032412672&quot;&gt;April 13, 2015&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Armed with this newfound wisdom, let’s define a class called &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupOps&lt;/code&gt; that wraps objects and adds methods for group operations on the underlying objects :
&lt;script src=&quot;https://gist.github.com/aakashns/f6c61a5f8af587dde756.js?file=GroupAnyVal.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;By making &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupOps&lt;/code&gt; an implicit class, we’re simply telling the compiler to add an implicit conversion from &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt; to &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupOps&lt;/code&gt; for types &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt; that are members of the type class &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt;. The above piece of code is equivalent to the following :
&lt;script src=&quot;https://gist.github.com/aakashns/f6c61a5f8af587dde756.js?file=GroupAnyVal2.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Since we cannot write a &lt;code class=&quot;highlighter-rouge&quot;&gt;def&lt;/code&gt; in the global scope, implicit classes can only be defined inside another class / trait / object, in this case &lt;code class=&quot;highlighter-rouge&quot;&gt;GroupSyntax&lt;/code&gt;. Let’s use the new syntax to simplify the code for &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup&lt;/code&gt; and the sum functions :
&lt;script src=&quot;https://gist.github.com/aakashns/f6c61a5f8af587dde756.js?file=Test.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Clearly, this technique substantially cleans up the interface for using group operations. But despite the benefits, you may not want to do this all the time, because :&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;It uses an implicit conversion. It is not easy to tell where the operator &lt;code class=&quot;highlighter-rouge&quot;&gt;|+|&lt;/code&gt; came from unless you know where to look. Many people find this confusing, and are going to avoid using it, no matter what you tell them.&lt;/li&gt;
  &lt;li&gt;It may potentially create a new instance of the type class each time you use it. If you find yourself using &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[(Int, Int)]&lt;/code&gt; 10 times in a block, you’re better off defining a local val &lt;code class=&quot;highlighter-rouge&quot;&gt;intPairGroup = Group[(Int, Int)]&lt;/code&gt; and using that, because &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[(Int, Int)]&lt;/code&gt; results in a call to &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup[Int, Int]&lt;/code&gt;, which instantiates a new object each time it is called. However, if you’re writing &lt;code class=&quot;highlighter-rouge&quot;&gt;a |+| b&lt;/code&gt; 10 times in a block, there is no easy way to avoid calling &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup[Int, Int]&lt;/code&gt; that many times.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Although the pretty syntax is nice to have, it comes at a cost. You should consider the use-cases of your type classes, and evaluate how they are affected by these costs. This might upset a few people, but I personally think that explicit is indeed better that implicit in this particular instance. So think twice before doing this.&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Type classes are awesome and you should use them everywhere. Make sure you do them right, and everyone will be happy. In addition to the techniques described in &lt;a href=&quot;/better-type-class.html#summary&quot;&gt;the previous post&lt;/a&gt; :&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Define a helper class to help reduce boilerplate for defining type class instances.
&lt;script src=&quot;https://gist.github.com/aakashns/c33c8cdd4b2d63bab60a.js?file=GroupAux.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Use a companion trait to automatically add the &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method to your type class companion objects.
&lt;script src=&quot;https://gist.github.com/aakashns/340068446e3fd59196be.js?file=TypeClassCompanion.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;You may define implicit classes to provide some nice syntax and pretty operators, but be aware of the costs, and also be aware that many people just won’t use them. This is best provided as an optional feature.
&lt;script src=&quot;https://gist.github.com/aakashns/f6c61a5f8af587dde756.js?file=GroupSyntax.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=b9434BoGkNQ&quot;&gt;That’s all folks!&lt;/a&gt;&lt;/p&gt;

</description>
        <pubDate>Mon, 13 Apr 2015 11:30:14 +0000</pubDate>
        <link>http://aakashns.github.io/better-type-class-2.html</link>
        <guid isPermaLink="true">http://aakashns.github.io/better-type-class-2.html</guid>
        
        
        <category>scala</category>
        
      </item>
    
      <item>
        <title>Scrap Your Type Class Boilerplate (1/2)</title>
        <description>&lt;p&gt;For the &lt;strong&gt;TL; DR&lt;/strong&gt; version, go straight to the &lt;a href=&quot;#summary&quot;&gt;Summary&lt;/a&gt;.&lt;/p&gt;

&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#introduction&quot; id=&quot;markdown-toc-introduction&quot;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#improvements&quot; id=&quot;markdown-toc-improvements&quot;&gt;Improvements&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#context-bounds&quot; id=&quot;markdown-toc-context-bounds&quot;&gt;Context Bounds&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#companion-objects-apply-method&quot; id=&quot;markdown-toc-companion-objects-apply-method&quot;&gt;Companion Object’s Apply Method&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#better-compilation-error-messages&quot; id=&quot;markdown-toc-better-compilation-error-messages&quot;&gt;Better Compilation Error Messages&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#summary&quot; id=&quot;markdown-toc-summary&quot;&gt;Summary&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;
&lt;p&gt;For a short introduction to type classes, see my &lt;a href=&quot;/type-class.html&quot;&gt;previous post&lt;/a&gt;. Type classes are a very useful pattern in Scala, that help keep your code base &lt;a href=&quot;https://www.youtube.com/watch?v=sVMES4RZF-8&quot;&gt;modular, decoupled and open to extension&lt;/a&gt;. Here is a somewhat &lt;s&gt;accurate&lt;/s&gt; inaccurate description of type classes :&lt;/p&gt;

&lt;blockquote class=&quot;twitter-tweet tw-align-center&quot; lang=&quot;en&quot;&gt;&lt;p&gt;Type classes in &lt;a href=&quot;https://twitter.com/hashtag/Scala?src=hash&quot;&gt;#Scala&lt;/a&gt; : Write less code, so that you can spend more time compiling it.&lt;/p&gt;&amp;mdash; Aakash N S (@aakashns) &lt;a href=&quot;https://twitter.com/aakashns/status/582276660248125441&quot;&gt;March 29, 2015&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Writing and using type classes, if not done properly, can entail some boilerplate and some fairly odd syntax for the user. Apart from being something to feel bad about, this can scare people away from using them, by making their heads blow up (at worst) and making code difficult to read or understand (at best). This post will try to identify and address some shortcomings in the implementation of a type class for &lt;a href=&quot;http://en.wikipedia.org/wiki/Group_(mathematics)&quot;&gt;groups&lt;/a&gt; and make it easier to use.&lt;/p&gt;

&lt;p&gt;Here is implementation of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; type class and its instances for a few types, as discussed in the &lt;a href=&quot;/type-class.html&quot;&gt;previous post&lt;/a&gt; :&lt;/p&gt;

&lt;script src=&quot;https://gist.github.com/aakashns/91d29ff8070440d816d8.js?file=Group.scala&quot;&gt; &lt;/script&gt;

&lt;p&gt;And here, the type class is used to define some generic functions :
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;h2 id=&quot;improvements&quot;&gt;Improvements&lt;/h2&gt;

&lt;p&gt;There are some problems with the above implementation :&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Any function that uses group operations needs type class instances to be passed in as implicit parameters.&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;
        &lt;p&gt;This makes the signature of the function unnecessarily long, especially for functions like &lt;code class=&quot;highlighter-rouge&quot;&gt;sumNonEmpty&lt;/code&gt;, which do not directly use any group operations, but simply call other functions that do. It also makes the code a little mysterious to read, because an argument is passed in but never used.&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;It is not immediately clear by looking at the function signature that the implicit parameter is a type class instance. There is no easy way to differentiate it from implicit parameters used for other purposes.&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;Implicit parameters have something of a bad reputation, mainly because they are easily misused / overused, leading to confusing code. It may seem crazy, but many people have an aversion to implicits, and will avoid writing methods with implicit parameters at all costs. Like this guy :&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote class=&quot;twitter-tweet tw-align-center&quot; lang=&quot;en&quot;&gt;&lt;p&gt;The problem with implicit parameters in &lt;a href=&quot;https://twitter.com/hashtag/Scala?src=hash&quot;&gt;#Scala&lt;/a&gt; is that you often have no idea where they come from or where they&amp;#39;re going.&lt;/p&gt;&amp;mdash; Aakash N S (@aakashns) &lt;a href=&quot;https://twitter.com/aakashns/status/582236918827610114&quot;&gt;March 29, 2015&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;

&lt;p&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The code for defining type class instances is rather verbose and repetitive (due to something I like to call &lt;em&gt;“the pain of overriding”&lt;/em&gt;), as can be seen in the implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;IntGroup&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;DoubleGroup&lt;/code&gt;, which are nearly identical, except for the types. If your type class defines lots of abstract methods or if you’re defining many instances of the type class, this can lead to a lot of boilerplate.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s try and fix these problems, and also other problems that arise in the process of fixing these.&lt;/p&gt;

&lt;h3 id=&quot;context-bounds&quot;&gt;Context Bounds&lt;/h3&gt;

&lt;p&gt;Scala provides syntactic sugar called context bounds to make the type class pattern slightly more visually appealing. With context bounds, the signature of &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup&lt;/code&gt; becomes :
&lt;script src=&quot;https://gist.github.com/aakashns/02fdca3a8fadafccb9e5.js?file=pairGroupSig.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;And the signatures of the &lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; functions become :
&lt;script src=&quot;https://gist.github.com/aakashns/02fdca3a8fadafccb9e5.js?file=sumSig.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;The only difference is that the annoying &lt;code class=&quot;highlighter-rouge&quot;&gt;(implicit tGroup: Group[T])&lt;/code&gt; in the parameter list is replaced by a much nicer &lt;code class=&quot;highlighter-rouge&quot;&gt;[T: Group]&lt;/code&gt; in the type parameter list. This is called a context bound, and it is simply syntactic sugar for passing in an instance of &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[T]&lt;/code&gt; as an implicit parameter to the function. However, the new function signature is more readable, and it is immediately clear that &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt; is a member of the type class &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With the implicit parameter gone from the signature, everyone will be happy, and we can all go home. Except we can’t, because we still need to access the parameter to call the group operations plus, minus and inverse on it. But how do we find the &lt;s&gt;man&lt;/s&gt; parameter with no name?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/uoWctOP.jpg&quot; alt=&quot;The Parameter With No Name&quot; class=&quot;center-image responsive-image&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;

&lt;p&gt;We find &lt;s&gt;him&lt;/s&gt; it using the &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly&lt;/code&gt; method, which, to quote &lt;a href=&quot;https://github.com/scala/scala/blob/v2.11.6/src/library/scala/Predef.scala#L130&quot;&gt;the official documentation&lt;/a&gt; (not kidding), is used &lt;em&gt;“for summoning implicit values from the nether world”&lt;/em&gt;. So you better not type &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly[Satan]&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly[Hitler]&lt;/code&gt; or something like that (alright, you can type it, I just did, but please don’t compile it).&lt;/p&gt;

&lt;p&gt;Using &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly&lt;/code&gt;, the new implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup&lt;/code&gt; looks like this :
&lt;script src=&quot;https://gist.github.com/aakashns/02fdca3a8fadafccb9e5.js?file=PairGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;And the &lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; functions look like this :
&lt;script src=&quot;https://gist.github.com/aakashns/02fdca3a8fadafccb9e5.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Great, so we replaced implicit parameters in function signatures with &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly[Group[T]]&lt;/code&gt; spewed all over the code base. Now you know I wasn’t kidding about heads exploding. I’ll let you decide which of the two styles is uglier, but the good news is, we can get rid of them both.&lt;/p&gt;

&lt;h3 id=&quot;companion-objects-apply-method&quot;&gt;Companion Object’s Apply Method&lt;/h3&gt;

&lt;p&gt;Let’s add an apply method to the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; companion object :
&lt;script src=&quot;https://gist.github.com/aakashns/fee27ed7ff3ff0c84d46.js?file=Group.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;As you might already know, the &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method is given special treatment in Scala, so that instead of writing &lt;code class=&quot;highlighter-rouge&quot;&gt;Group.apply[T]&lt;/code&gt; to call the method, you can write &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[T]&lt;/code&gt; and the compiler will  replace it with &lt;code class=&quot;highlighter-rouge&quot;&gt;Group.apply[T]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The method itself is so simple that it feels almost unnecessary to even define it, let alone devote an entire section of this blog post to it (after all, the signature of the method is longer that its body). But bear with me for a moment. Using this &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method, the implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;pairGroup&lt;/code&gt; now looks like this :
&lt;script src=&quot;https://gist.github.com/aakashns/fee27ed7ff3ff0c84d46.js?file=PairGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;And the &lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; functions look like this :
&lt;script src=&quot;https://gist.github.com/aakashns/fee27ed7ff3ff0c84d46.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;I encourage you to take a moment and marvel at what we have achieved here :&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;The most obvious difference is that there is no more &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly[Group[T]]&lt;/code&gt;. But if you look a little more closely, you will notice that there are no signs of anything implicit anywhere outside the definition of the type class. Someone using the type class in their functions does not need to know that the implementation uses implicits. In fact, they do not even need to know what implicits are, let alone &lt;em&gt;“summon them from the nether world”&lt;/em&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;With the context bound syntax &lt;code class=&quot;highlighter-rouge&quot;&gt;[T: Group]&lt;/code&gt; in the function signature and the apply method syntax &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[T]&lt;/code&gt; to get the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; for type &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt;, type classes looks like a feature of the language itself. Even your editor will congratulate you on this accomplishment, by syntax highlighting &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[T].plus(...)&lt;/code&gt; with pretty colors.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, with context bounds and the apply method, you can make the lives of the users of your type classes much easier, by letting them bask in the unexpected virtue of ignorance (or &lt;a href=&quot;http://www.imdb.com/title/tt2562232/&quot;&gt;Birdman&lt;/a&gt;). Also, they can no longer make lame excuses for not using your type classes.&lt;/p&gt;

&lt;h3 id=&quot;better-compilation-error-messages&quot;&gt;Better Compilation Error Messages&lt;/h3&gt;

&lt;p&gt;Okay, here’s the thing, I lied to you earlier about the user not needing to know about implicits (but only because the truth wasn’t good enough, and you deserved to have your faith rewarded). Trying to compile the following piece code :
&lt;script src=&quot;https://gist.github.com/aakashns/ee49091b62853114fb04.js?file=test.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;will lead to the following compilation error :
&lt;script src=&quot;https://gist.github.com/aakashns/ee49091b62853114fb04.js?file=error.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Ah! &lt;em&gt;The &lt;s&gt;Empire&lt;/s&gt; Implicit Strikes Back!&lt;/em&gt; This the kind of cryptic error message that will make people go &lt;em&gt;“What? Implicit what? Evidence? What? Which parameter? :-( Screw this! I hate Scala!”&lt;/em&gt; And even if you do know that the implementation of type classes uses implicits, this error is message it not very helpful because it takes an additional mental step to figure out that it’s basically saying that the compiler couldn’t find an instance of the type class &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; for &lt;code class=&quot;highlighter-rouge&quot;&gt;Boolean&lt;/code&gt;. Fortunately, Scala gives us a way of fixing this too (is there anything Scala does &lt;em&gt;NOT&lt;/em&gt; give?), using a compiler annotation :
&lt;script src=&quot;https://gist.github.com/aakashns/ee49091b62853114fb04.js?file=Group.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;That’s it! The error message when trying to compile &lt;code class=&quot;highlighter-rouge&quot;&gt;sum(Seq(true, false))&lt;/code&gt; will now read :
&lt;script src=&quot;https://gist.github.com/aakashns/ee49091b62853114fb04.js?file=error2.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;No more cryptic error messages! No more implicit parameters! No more &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitly&lt;/code&gt; and no more nether world-summoning! Type classes FTW! Developers be like :&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://media.giphy.com/media/WijMCD1r9hOIE/giphy.gif&quot; alt=&quot;&amp;quot;Developers celebrating&amp;quot;&quot; class=&quot;center-image responsive-image&quot; /&gt;&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;People don’t like implicits. People don’t like unreadable code. People don’t like cryptic error messages. Make your type classes easy to use. Don’t give people reasons not to use your them.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Define an &lt;code class=&quot;highlighter-rouge&quot;&gt;apply&lt;/code&gt; method on the companion object to allow easy access to type class instances :
&lt;script src=&quot;https://gist.github.com/aakashns/fee27ed7ff3ff0c84d46.js?file=Group.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Use and encourage people to use context bounds (and not implicit parameters) :
&lt;script src=&quot;https://gist.github.com/aakashns/fee27ed7ff3ff0c84d46.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Use the &lt;code class=&quot;highlighter-rouge&quot;&gt;implicitNotFound&lt;/code&gt; annotation to provide better compilation error messages :
&lt;script src=&quot;https://gist.github.com/aakashns/ee49091b62853114fb04.js?file=Group.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s it for the first part of this post. As you might have noticed, we haven’t addressed the second concern raised earlier. We will address it in the &lt;a href=&quot;/better-type-class-2.html&quot;&gt;second part&lt;/a&gt;, and we will also cover a other few techniques to make your type classes even better, especially for you, who’s doing the hard work of defining all the instances.&lt;/p&gt;

</description>
        <pubDate>Sun, 29 Mar 2015 11:30:14 +0000</pubDate>
        <link>http://aakashns.github.io/better-type-class.html</link>
        <guid isPermaLink="true">http://aakashns.github.io/better-type-class.html</guid>
        
        
        <category>scala</category>
        
      </item>
    
      <item>
        <title>Type Classes in Scala</title>
        <description>&lt;p&gt;Consider the following functions :&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; : which takes a list of integers and returns their sum.
&lt;script src=&quot;https://gist.github.com/aakashns/4599e5db4b28e02f79b9.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;sumDifference&lt;/code&gt; : which takes two lists of integers and returns the difference of the their sums.
&lt;script src=&quot;https://gist.github.com/aakashns/4599e5db4b28e02f79b9.js?file=sumDifference.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;sumNonEmpty&lt;/code&gt; : which takes a list of integers and returns an &lt;code class=&quot;highlighter-rouge&quot;&gt;Option[Int]&lt;/code&gt;, which is &lt;code class=&quot;highlighter-rouge&quot;&gt;None&lt;/code&gt; if the list is empty, and a &lt;code class=&quot;highlighter-rouge&quot;&gt;Some&lt;/code&gt; containing the sum of the members otherwise.
&lt;script src=&quot;https://gist.github.com/aakashns/4599e5db4b28e02f79b9.js?file=sumNonEmpty.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Suppose we want to generalize these functions to work on lists of some other type, such as &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt;s, pairs of integers i.e. &lt;code class=&quot;highlighter-rouge&quot;&gt;(Int, Int)&lt;/code&gt; with &lt;code class=&quot;highlighter-rouge&quot;&gt;(x1, x2) + (y1, y2)&lt;/code&gt; defined as &lt;code class=&quot;highlighter-rouge&quot;&gt;(x1 + y1, x2 + y2)&lt;/code&gt;, or pairs of &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt;s. Take a moment and think about how you would do it.
All these types seem to naturally support the operations addition and subtraction, but this fact is not encoded in their inheritance hierarchy, which makes it extremely difficult to write generic functions that work for all of them.&lt;/p&gt;

&lt;p&gt;To solve this problem, let’s define a trait called &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; :
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=Group.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; is a generic trait, which takes a type parameter &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt; and declares the operations plus, minus and inverse for objects of type &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt;, as well as an element zero. Note that minus is defined using plus and inverse because &lt;code class=&quot;highlighter-rouge&quot;&gt;x - y = x + (-y)&lt;/code&gt;(how clever!).&lt;/p&gt;

&lt;p&gt;Groups are a &lt;a href=&quot;http://en.wikipedia.org/wiki/Group_(mathematics)&quot;&gt;real thing&lt;/a&gt;, and the operation plus needs to be associative i.e. &lt;code class=&quot;highlighter-rouge&quot;&gt;(x + y) + z&lt;/code&gt; should be equal to &lt;code class=&quot;highlighter-rouge&quot;&gt;x + (y + z)&lt;/code&gt;, otherwise we may get weird results.&lt;/p&gt;

&lt;p&gt;Instances of the trait &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; should ideally be defined as &lt;em&gt;implicit&lt;/em&gt; members of the object &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt;, which lives is the same file as the trait. It is called the &lt;em&gt;companion object&lt;/em&gt; of the trait. When the Scala compiler needs to supply an implicit parameter of type &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[T]&lt;/code&gt;, it looks inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; companion object. So, we won’t need to pass around &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; instances explicitly while writing and using functions that depend on group operations.&lt;/p&gt;

&lt;p&gt;Let’s define an instance of the trait for integers (inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; object, of course):
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=IntGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;The instance for &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt; looks almost identical, except for the types :
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=DoubleGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;Let’s try something a little more interesting. Here’s a method that produces a an instance of &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; for the pair &lt;code class=&quot;highlighter-rouge&quot;&gt;(T1, T2)&lt;/code&gt;, if it can find instances of &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; for &lt;code class=&quot;highlighter-rouge&quot;&gt;T1&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;T2&lt;/code&gt; :
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=PairGroup.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;This single method will automatically provide &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; instances for &lt;code class=&quot;highlighter-rouge&quot;&gt;(Int, Int)&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;(Int, Double)&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;(Double, Int)&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;(Double, Double)&lt;/code&gt; whenever we need them. Isn’t that neat?&lt;/p&gt;

&lt;p&gt;Alright, now that we’ve done all the hard work, let’s use the trait to make our &lt;code class=&quot;highlighter-rouge&quot;&gt;sum&lt;/code&gt; functions generic :
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=sum.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;With these small modifications, you can now use these functions on lists of any type &lt;code class=&quot;highlighter-rouge&quot;&gt;T&lt;/code&gt; for which the compiler can find an implicit object of type &lt;code class=&quot;highlighter-rouge&quot;&gt;Group[T]&lt;/code&gt;:
&lt;script src=&quot;https://gist.github.com/aakashns/108da2dfc2b6d772f544.js?file=test.scala&quot;&gt; &lt;/script&gt;&lt;/p&gt;

&lt;p&gt;That’s it! That’s the type class pattern. &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; is called a type class (because it represents a &lt;em&gt;class of types&lt;/em&gt; that support group operations), and the types &lt;code class=&quot;highlighter-rouge&quot;&gt;Int&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;Double&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;(Int, Int)&lt;/code&gt; etc. are called members of the type class &lt;code class=&quot;highlighter-rouge&quot;&gt;Group&lt;/code&gt; because the compiler can find instances of the type class for these types.&lt;/p&gt;

&lt;p&gt;This post merely scratches the surface of the use cases and benefits of using type classes in Scala. Type classes are awesome and you should use them all over your code base. There are many great resources (much better than this one) for learning about type classes in Scala, like &lt;a href=&quot;https://www.youtube.com/watch?v=sVMES4RZF-8&quot;&gt;this&lt;/a&gt;, &lt;a href=&quot;http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html&quot;&gt;this&lt;/a&gt; and &lt;a href=&quot;https://blog.safaribooksonline.com/2013/05/28/scala-type-classes-demystified/&quot;&gt;this&lt;/a&gt;. The only reason this post exists is so that I can point out the deficiencies in this naive implementation, and show you how to make it much better &lt;a href=&quot;/better-type-class.html&quot;&gt;in my next post&lt;/a&gt;.&lt;/p&gt;

</description>
        <pubDate>Fri, 27 Mar 2015 11:30:14 +0000</pubDate>
        <link>http://aakashns.github.io/type-class.html</link>
        <guid isPermaLink="true">http://aakashns.github.io/type-class.html</guid>
        
        
        <category>scala</category>
        
      </item>
    
  </channel>
</rss>
