{"id":791,"date":"2016-10-19T14:47:12","date_gmt":"2016-10-19T14:47:12","guid":{"rendered":"http:\/\/blog.stratio.com\/?p=791"},"modified":"2023-09-20T13:47:39","modified_gmt":"2023-09-20T13:47:39","slug":"developers-guide-scala-implicit-values-part","status":"publish","type":"post","link":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/","title":{"rendered":"The Developer\u2019s Guide to Scala Implicit Values (Part II)"},"content":{"rendered":"<p style=\"text-align: right;\"><em style=\"font-size: inherit;\">Imagine a rectangular grid of cells, in which each cell has a value &#8211; Either black (dead) or white (alive). And imagine that:<\/em><\/p>\n<blockquote>\n<ol>\n<li><em>Any live\u00a0cell\u00a0with two or three live neighbors survives for the next generation.<\/em><\/li>\n<li><em>Any\u00a0cell\u00a0with four or more neighbors dies from overpopulation.<\/em><\/li>\n<li><em>Any\u00a0cell\u00a0with one or no neighbors dies from isolation.<\/em><\/li>\n<li><em>Any dead cell with\u00a0exactly three neighbors comes to life.<\/em><\/li>\n<\/ol>\n<\/blockquote>\n<p style=\"text-align: justify;\"><em>These are the four\u00a0simple rules of\u00a0<a href=\"https:\/\/en.wikipedia.org\/wiki\/Conway%27s_Game_of_Life\" target=\"_blank\" rel=\"noopener\">Conway&#8217;s Game of Life<\/a>\u00a0. You could hardly imagine a simpler set of rules to code on your computer and\u00a0you\u00a0wouldn&#8217;t expect any interesting result at all, but&#8230;<\/em><\/p>\n<p style=\"text-align: center;\">Behold the wonders of its hidden\u00a0might!<!--more--><\/p>\n<p><iframe loading=\"lazy\" title=\"epic conway&#039;s game of life\" width=\"770\" height=\"433\" src=\"https:\/\/www.youtube.com\/embed\/C2vgICfQawE?start=146&#038;feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/p>\n<p style=\"text-align: justify;\">The Conway&#8217;s Game of Life is an example of how a simple set of rules can produce amazing and totally\u00a0unexpected results.<\/p>\n<p style=\"text-align: justify;\"><a href=\"http:\/\/blog.stratio.com\/developers-guide-scala-implicit-values-part-1\/\" target=\"_blank\" rel=\"noopener\">In the previous post<\/a>, we agreed that the rules governing Scala&#8217;s implicit context weren&#8217;t complex at all, all of it can be summed up as:\u00a0<em>Mark some parameters as\u00a0special, let the compiler know there are some values and some functions it can use when it is struggling with your code compilation&#8230; and hope it can manage to fill the gaps.<\/em><\/p>\n<p style=\"text-align: justify;\">No matter how simple the implicit context rules are, they are definitely\u00a0\u00a0more complex than Conway&#8217;s. And, as in his\u00a0little game of life, they bring complex\u00a0results that, sometimes, make Scala newcomers sweat. However,\u00a0under the developer&#8217;s control, they can become the glue\u00a0that holds\u00a0the most important Scala patterns together &#8211; the dark matter behind its visible universe. In this article we&#8217;ll walk through some examples of the marvels<span style=\"color: #000000;\">\u00a0implicits c<\/span>an lead to.<\/p>\n<h2>Scala&#8217;s Dark Matter<\/h2>\n<p style=\"text-align: justify;\">Whereas it is theorised that\u00a0some non-visible matter\u00a0is responsible for helping maintain the galaxies together, we know for sure that some non-straightforwardly-visible values and functions hold many Scala constructions together. Let&#8217;s see some of these constructions.<\/p>\n<h2>Implicits application 101: The hidden context<\/h2>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignleft\" src=\"http:\/\/www.mememaker.net\/static\/images\/memes\/4327896.jpg\" width=\"151\" height=\"159\" \/><\/p>\n<p style=\"text-align: justify;\">Imagine you&#8217;re enjoying a session of peer programming. Your mate has the keyboard while you keep your eyes wide open,\u00a0eager to suggest changes and solutions. Wouldn&#8217;t you find it stupid to repeat your friend&#8217;s name every\u00a0time you address her\/him? It is\u00a0<strong>implicit\u00a0<\/strong>that you are talking to her\/him and not to another person who may be walking around!<\/p>\n<p style=\"text-align: justify;\">Why should it be any different in a block of code which\u00a0repeatedly interacts with\u00a0a\u00a0service?!<\/p>\n<p style=\"text-align: justify;\">If you come from Java you might be thinking:\u00a0<em>&#8220;What are you, dude, some kind of slacker?&#8221;.\u00a0<\/em>Well, you also keep writing &#8220;;&#8221;s which, let&#8217;s be honest, are ignored by everybody&#8217;s brain&#8230; \u00a0Lets give a concrete example from\u00a0<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/concurrent\/Future.html\" target=\"_blank\" rel=\"noopener\">Oracle&#8217;s documentation on Java Futures<\/a>:<\/p>\n<pre class=\"lang:scala decode:true\" title=\"Java's creation of futures\">ExecutorService executor = ...\n  \nFuture&lt;String&gt; futureA = executor.submit(new Callable&lt;String&gt;() {\n         public String call() {\n             ...\n         }});\n\nFuture&lt;String&gt; futureB = executor.submit(new Callable&lt;String&gt;() {\n         public String call() {\n             ...\n         }});\n\n<\/pre>\n<p style=\"text-align: justify;\">It&#8217;s like saying: &#8220;He<em>y you!\u00a0<strong>Executor<\/strong>, do this<\/em>&#8220;, &#8220;He<em>y you!\u00a0<strong>Executor<\/strong>, do this other thing&#8221;.\u00a0<\/em>It would be\u00a0more comfortable, by far, to just agree to use a concrete executor at the beginning\u00a0of a code block, thus avoiding writing its identifier over and over again. Take a look at fairly equivalent code written in Scala:<\/p>\n<pre class=\"lang:default decode:true\" title=\"Scala's creation of futures\">implicit val executor: ExecutionContextExecutor = ...\n\nval futureA = Future[String] { ... }\nval futureB = Future[String] { ... }<\/pre>\n<p style=\"text-align: justify;\">Now take a closer (unfolded) look at the creation of the first future:\u00a0<span class=\"lang:scala decode:true crayon-inline \">val futureA = Future[String] { &#8230; }<\/span>\u00a0. This is calling for\u00a0<a href=\"http:\/\/www.scala-lang.org\/api\/current\/index.html#scala.concurrent.Future$\" target=\"_blank\" rel=\"noopener\"><em>Future<\/em><\/a>\u00a0objects to<em>\u00a0apply<\/em>\u00a0factory method&#8230;<\/p>\n<pre class=\"lang:default decode:true \">val futureA = Future.apply[String] { ... }<\/pre>\n<p>&#8230;with the following method signature indicating it can get its executor parameter from an implicit value:<\/p>\n<pre class=\"lang:scala decode:true\">def apply[T](body: \u21d2 T)(implicit executor: ExecutionContext): Future[T]<\/pre>\n<p style=\"text-align: justify;\"><span style=\"color: #000000;\">Sound familiar?\u00a0<em>apply&#8217;s\u00a0<\/em><em>body\u00a0<\/em>parameter<em>\u00a0<\/em>is to Java&#8217;s\u00a0<em><a style=\"color: #000000;\" href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/concurrent\/Executor.html#execute-java.lang.Runnable-\">Executor#execute<\/a><\/em>\u00a0<em>command\u00a0<\/em>parameter<em>\u00a0<\/em>what the\u00a0<em>executor\u00a0<\/em>implicit\u00a0parameter is to the\u00a0<em>Executor\u00a0<\/em>instance repeatedly and explicitly referred to in Java.<\/span><\/p>\n<p style=\"text-align: justify;\">This pattern easily\u00a0comes up\u00a0when developing \u00a0a context dependent library and it isn&#8217;t difficult at all to develop a quick example.<\/p>\n<p style=\"text-align: justify;\"><em>You are developing a platform game in which\u00a0your open source hero, Tux, moves around a stage, dodging and killing enemies, collecting rewards&#8230;<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"http:\/\/imagenes.es.sftcdn.net\/es\/scrn\/33000\/33590\/supertux-38.jpg\" width=\"323\" height=\"242\" \/><\/p>\n<p style=\"text-align: justify;\"><em>Your task is to write a\u00a0<strong>comfortable<\/strong>\u00a0collision detection module whereby its users can easily determine how the game reacts to different positions of our hero, at concrete times<span style=\"color: #000000;\">\u00a0given<\/span>\u00a0a scenario.\u00a0<\/em>A first approach\u00a0could be something like&#8230;<\/p>\n<pre class=\"lang:scala decode:true\">case class Stage(...)\ncase class TuxState(pos: (Int, Int), points: Int, lives: Int)\n...\ndef newTuxState(tuxState: TuxState, t: Time, stage: Stage): TuxState = ???\n<\/pre>\n<p>and it could\u00a0be used to run the game loop step by step as follows &#8230;<\/p>\n<pre class=\"lang:scala decode:true\">def calculateNextStage(implicit stage: Stage): Stage = ???\n\ndef runGameFrame(t: Time, prevTuxSt: TuxState, stage: Stage): GameStats = {\n\n  doPaintStage(t, stage) \/\/Some side...\n  doPaintTuxSprite(prevTuxSt) \/\/... effects.\n  ...\n\n  tuxSt = newTuxState(prevTuxSt, t, stage)\n\n  nextStage = if(goalReached(tuxSt, stage)) calculateNextStage(stage) else stage\n\n  ...\n\n if(gameOver) stats  \n else runGameFrame(t + (1 turn), tuxSt, nextStage)\n\n}\n<\/pre>\n<p style=\"text-align: justify;\">Isn&#8217;t\u00a0<em>stage\u00a0<\/em>a context in the game solution? It doesn&#8217;t vary over a game-loop step (<em>runGameFrame<\/em>) and is constantly and explicitly used by many of the operations performed. By noticing this and making it an implicit parameter for these operations we get a much clearer and concise code:<\/p>\n<pre class=\"lang:scala decode:true\">...\ndef newTuxState(tuxState: TuxState, t: Time)(implicit stage: Stage): TuxState = ???\ndef calculateNextStage(implicit stage: Stage): Stage\n...\n\ndef runGameFrame(t: Time, prevTuxSt: TuxState)(implicit stage: Stage): (TuxState, Stage) = {\n\n  doPaintStage(t) \/\/Some side...\n  doPaintTuxSprite(prevTuxSt) \/\/... effects.\n  ...\n\n  tuxSt = newTuxState(prevTuxSt, t)\n\n  ...\n  \n  if(gameOver) stats \n  else runGameFrame(t + (1 turn), tuxSt) {\n    if(goalReached(tuxSt)) calculateNextStage else stage\n  }  \n\n}<\/pre>\n<h2>Types, tourists at run-time<\/h2>\n<p style=\"text-align: justify;\">Well, gluing contexts to methods, functions or constructor calls is cool, saves time and keystrokes\u00a0and those are great advantages\u00a0of a language for which developers aren&#8217;t paid by the written byte.<\/p>\n<p style=\"text-align: justify;\">Now is time to meet a pattern providing something you wouldn&#8217;t get by other means: Run-time types awareness.<\/p>\n<p style=\"text-align: justify;\">Types are citizens of the compilation time, they determine how &#8211; or if &#8211; your program will compile. However, without the help of the goddess of reflection, the only way to make decisions upon value types at run-time is through pattern matching:<\/p>\n<pre class=\"lang:scala decode:true\">val obj: Any = 1\n\nobj match { \n    case _: Int =&gt; println(\"It's an integer!\"); \n    case _ =&gt; println(\"I don't know what is it, but is not an Integer.\") \n}<\/pre>\n<p style=\"text-align: justify;\">However, the underlying mechanism behind type matching is nothing else than JVM&#8217;s\u00a0<span class=\"lang:java decode:true crayon-inline \">instanceof<\/span>\u00a0operator which is constrained by JVM&#8217;s type erasure. This means that all types generated by a type generator (a genetic type) are\u00a0classified as instances of the same class. Have you ever tried to do something like the following?<\/p>\n<pre class=\"lang:scala decode:true\">val la = List(1,2,3)\nval lb = List(\"Daisy\", \"Daisy\", \"give\", \"me\", \"your\", \"answer\", \"do\")\n\nval l = lb\n\nl match {\n  case _: List[Int] =&gt; println(\"It's a list of integers\")\n  case _: List[String] =&gt; println(\"It's a list of strings\")\n}<\/pre>\n<p style=\"text-align: justify;\">If you type the above code into Scala&#8217;s REPL it&#8217;ll yield:\u00a0<em>&#8220;It&#8217;s a list of integers&#8221;<\/em>\u00a0Ups!<\/p>\n<p style=\"text-align: justify;\">The matter is that the above code is, in some way, like writing the following Java snippet where the parametric type has completely disappeared from the list type:<\/p>\n<pre class=\"lang:java decode:true\">if(lb instanceof List) System.out.println(\"It's a list of integers\")\nelse if(lb instanceof List) System.out.println(\"It's a list of strings\")\n<\/pre>\n<p style=\"text-align: justify;\"><span style=\"color: #000000;\">As the first condition is true, we can understand why the\u00a0pattern match isn&#8217;t working.\u00a0<\/span><\/p>\n<p style=\"text-align: justify;\">What a shame of a language if we are not able to make such a decision at run-time! &#8230; But don&#8217;t run from Scala just yet! It provides a way. It always does&#8230;<\/p>\n<p style=\"text-align: justify;\">The way to do it,\u00a0is by leveraging our dark matter:\u00a0<strong>Implicit values<\/strong>. The Scala compiler automatically provides implicit values\u00a0for any of the types generated by\u00a0<span class=\"lang:scala decode:true crayon-inline\">TypeTag[T]<\/span>\u00a0. If you don&#8217;t believe me, check for yourself:<\/p>\n<pre class=\"lang:scala decode:true\">import scala.reflect.runtime.universe._\n\nimplicitly[TypeTag[Int]]\n\n\/\/ res0: reflect.runtime.universe.TypeTag[Int] = TypeTag[Int]\n\nimplicitly[TypeTag[List[Int]]]\n\n\/\/ res1: reflect.runtime.universe.TypeTag[List[Int]] = TypeTag[scala.List[Int]]\n\nimplicitly[TypeTag[List[String]]]\n\n\/\/ res2: reflect.runtime.universe.TypeTag[List[String]] = TypeTag[scala.List[String]]\n\/\/ It's noticing the nuance behind the parametric type! Not as that silly \"instanceof\"...\n\ncase class RuntimeTourist[T]()\n\nimplicitly[TypeTag[RuntimeTourist[Int]]]\n\n\/\/ res3: reflect.runtime.universe.TypeTag[RuntimeTourist[Int]] = TypeTag[RuntimeTourist[Int]]\n\n\/\/ You know-it-all compiler! TAKE THIS!!\n\nimplicitly[TypeTag[RuntimeTourist[RuntimeTourist[RuntimeTourist[Int]]]]]\n\/* res4: reflect.runtime.universe.TypeTag[RuntimeTourist[RuntimeTourist[RuntimeTourist[Int]]]] =\n                TypeTag[RuntimeTourist[RuntimeTourist[RuntimeTourist[Int]]]]\n\nThis thing goes deep, and keeps track of nested parametric types.\n\n*\/\n\n\/\/... GOTCHA!!\n\nimplicitly[TypeTag[List[Map[List[Int], RuntimeTourist[List[String]]]]]]\n\n\/* res5: reflect.runtime.universe.TypeTag[List[Map[List[Int],RuntimeTourist[List[String]]]]] =\n   TypeTag[scala.List[Map[scala.List[Int],RuntimeTourist[scala.List[String]]]]]\n*\/\n\n\/\/ It will work, no matter how complex the type parametrization is.<\/pre>\n<p style=\"text-align: justify;\">The point now is to use these labels to make decisions based on the types at run time. Remember the unsatisfactory attempt with pattern matching? Let&#8217;s try again. This time using the new cutting edge dark matter drive:<\/p>\n<pre class=\"lang:scala decode:true\">import scala.reflect.runtime.universe.{TypeTag, typeOf}\n\ndef whatIsIt[T](l: T)(implicit tag: TypeTag[T]): Unit = {\n  if(tag.tpe =:= typeOf[List[Int]]) println(\"It's a list of integers\")\n  else if(tag.tpe =:= typeOf[List[String]]) println(\"It's a list of strings\")\n}\n\nwhatIsIt(la)\n\/\/ It's a list of integers\n\nscala&gt; whatIsIt(lb)\n\/\/ It's a list of strings\n<\/pre>\n<p style=\"text-align: justify;\">Yeah! OK, so far so good &#8211; but don&#8217;t think this is the only way, or even the best way to defeat type erasure. But this post is about implicit things.<\/p>\n<p style=\"text-align: justify;\">I&#8217;d be more than happy to show you more about types at run time, but\u00a0this is like a Star Wars film (the oldies)\u00a0&#8211; if you want to know how the Death Star plans were stolen &#8211; chapter and verse &#8211; you&#8217;ll have to wait for Rogue One<b>\u2122<\/b>&#8230;<\/p>\n<p style=\"text-align: justify;\">However, there is something related to implicits and to\u00a0implicits only, which make the above code a lot less verbose&#8230;<\/p>\n<h3>Implicit type bounds<\/h3>\n<p style=\"text-align: justify;\">Coming back to\u00a0<span class=\"lang:scala decode:true crayon-inline \">whatIsIt[T](l: T)(implicit tag: TypeTag[T]): Unit<\/span>\u00a0. Look at the second parameter list. Yes, the one for implicit parameters. It is worth noting that the code pattern for methods like\u00a0<span class=\"lang:scala decode:true crayon-inline\">someMethod[T](&#8230;)(implicit SomeParametricType[T])<\/span>\u00a0is so common that the language provides a shortcut for it:\u00a0<span class=\"lang:scala decode:true crayon-inline\">someMethod(&#8230;)[T : SomeParametricType]<\/span>\u00a0and our\u00a0<span class=\"lang:scala decode:true crayon-inline \">whatIsIt<\/span>\u00a0could make good use of it:<\/p>\n<pre class=\"lang:scala decode:true\">def whatIsIt[T : TypeTag](l: T): Unit = {\n  val tag = implicitly[TypeTag[T]]\n  if(tag.tpe =:= typeOf[List[Int]]) println(\"It's a list of integers\")\n  else if(tag.tpe =:= typeOf[List[String]]) println(\"It's a list of strings\")\n}\n<\/pre>\n<p style=\"text-align: justify;\">Don&#8217;t you love this language?!<\/p>\n<p style=\"text-align: justify;\">To conclude\u00a0this interlude, a last piece of advice: Don&#8217;t think that implicit type bounds are incompatible with other types of bounds. The following piece of code is not only correct, but also represents a common use of type bounds:<\/p>\n<pre class=\"lang:scala decode:true \">\/\/(for a class C)\n\ndef f[T &lt;: C : TypeTag, S](x: T): S = ???<\/pre>\n<p style=\"text-align: justify;\">By the way, the implicit parameter for the TypeTag is known as\u00a0<strong><em>the implicit evidence for T<\/em><\/strong>.<\/p>\n<h2 style=\"text-align: justify;\">The magnetic attraction of the &#8220;classy\u00a0type&#8221;<\/h2>\n<p style=\"text-align: justify;\">Have you ever tried to add functionality to a case class? Have you ever wanted to work with a third party class as if it was a subclass of one of yours?<\/p>\n<p style=\"text-align: justify;\"><em>Farm Management Ltd. has given us a great library with classes to represent animals in a farm management system. Among others, it contains the classes: Cat, Cow, Dog and Unicorn. All these classes implement\u00a0the interface\u00a0Animal&#8230;<br \/>\n<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"http:\/\/i.imgur.com\/dGWXBQY.png\" width=\"271\" height=\"137\" \/><\/p>\n<p style=\"text-align: justify;\"><em>Animal establishes that all its\u00a0implementations should offer the operation\u00a0<span class=\"lang:scala decode:true crayon-inline\">takeCareOf(caretaker: PersonId, date: Date): ScheduledActivity<\/span>\u00a0 which returns a ScheduledActivity value representing a programmed activity in the managed farm operations.<br \/>\nOur goal is to expand the farm management system so it can also manage activities related to equipment maintenance &#8211; such as fencing, fixing machinery, &#8230;\u00a0we then provide classes representing &#8220;things to be maintained&#8221; which are not animals:<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"http:\/\/i.imgur.com\/wHrRp72.png\" width=\"242\" height=\"162\" \/><\/p>\n<p style=\"text-align: justify;\"><em>Equipment establishes the operation\u00a0<span class=\"lang:scala decode:true crayon-inline\">fix(worker: PersonId, date: Date): ScheduledActivity<\/span>\u00a0. So far so good&#8230; but now a problem arises: How will our management system be able to integrate animals to be taken care of with machines to be fixed in a common scheduler for all the farm activities? Remember, we CAN NOT modify the class Animal, that is: We CAN NOT create a common ancestor for\u00a0<span class=\"lang:default decode:true crayon-inline \">Equipment<\/span>\u00a0and\u00a0<span class=\"lang:default decode:true crayon-inline \">Animal<\/span>\u00a0to polimorphically work with their implementations&#8217; instances.<\/em><\/p>\n<p style=\"text-align: justify;\">An experienced Java developer\u00a0would probably say something like\u00a0<em>&#8220;What&#8217;s the matter bro?! \u00a0Wrap it up and carry on!&#8221;\u00a0<\/em>meaning:<em>\u00a0Just create a wrapper for the class provided by Farm Management Ltd.\u00a0<\/em><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"http:\/\/i.imgur.com\/nALL99d.png?1\" width=\"518\" height=\"230\" \/><\/p>\n<pre class=\"lang:scala decode:true \">trait Maintainable {\n  def scheduleMaintenance(worker: PersonId, date: Date): ScheduledActivity\n}\n\ntrait Equipment extends Maintainable\n\ncase class Car() extends Equipment {\n  def scheduleMaintenance(worker: PersonId, date: Date): ScheduledActivity = ???\n}\n\ncase class Fence() extends Equipment {\n  def scheduleMaintenance(worker: PersonId, date: Date): ScheduledActivity = ???\n}\n\ncase class Tractor() extends Equipment {\n  def scheduleMaintenance(worker: PersonId, date: Date): ScheduledActivity = ???\n}\n\ncase class AnimalWrapper(animal: Animal) extends Maintainable {\n  def scheduleMaintenance(worker: PersonId, date: Date): ScheduledActivity = animal.takeCareOf(worker, date)\n}<\/pre>\n<p style=\"text-align: left;\">This is great, but not so comfortable. All\u00a0<em>Animal<\/em>\u00a0instances need to be manually boxed within\u00a0<em>AnimalWrapper\u00a0<\/em>instances. That is, we need a kind of\u00a0<strong>force<\/strong>\u00a0to glue the farm element families together.\u00a0e.g:<\/p>\n<pre class=\"lang:scala decode:true\">val animals = Cat()::Dog()::Unicorn()::Nil\nval vehicles = Car()::Tractor()::Nil\n\nval butchTheFarmer: PersonId = { ... }\nval sarahTheMechanic: PersonId = { ... }\n\n\nval scheduledTasks = (\n                      animals map (animal =&gt; AnimalWrapper(animal).scheduleMaintainance(butchTheFarmer, tomorrow))\n                     ) ++ (\n                      vehicles map (_.scheduleMaintainance(sarahTheMechanic, tomorrow))\n                     )<\/pre>\n<p style=\"text-align: justify;\">In the above example, that force is the explicit boxing of animals (<span class=\"lang:scala decode:true crayon-inline\">AnimalWrapper(animal)<\/span>\u00a0). What an inconvenience to manually box every single\u00a0<em>Animal\u00a0<\/em>instance you want to integrate in your management system!<\/p>\n<p style=\"text-align: left;\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/cdn.meme.am\/instances\/24488865.jpg\" width=\"240\" height=\"240\" \/><\/p>\n<p style=\"text-align: justify;\">No! We are well into the 21st century. Besides, we agree that we have been\u00a0kind of slack, don&#8217;t we? There must be a better way!<\/p>\n<p style=\"text-align: justify;\"><img loading=\"lazy\" decoding=\"async\" class=\"alignleft\" src=\"http:\/\/i.imgur.com\/tuFExZl.png\" width=\"250\" height=\"176\" \/>What we are actually searching\u00a0for is a way to\u00a0<strong>categorise\u00a0<\/strong>types, or classes, after their declaration, some kind of\u00a0<strong>delayed\u00a0type classification<\/strong>. By using old school OOP inheritance we are classifying our types when they are defined, therefore the integration problems with third party entities. To overcome this kind of situation, it would be cool to have a mechanism which allows us to set classes of entities with a defined set of operations and to link types of instances to some classes whenever needed, not only at definition time. This idea is not new and such a mechanism exists for Haskell since 1990:\u00a0<strong><a href=\"http:\/\/learnyouahaskell.com\/making-our-own-types-and-typeclasses#typeclasses-102\">Type Classes<\/a>.<\/strong><\/p>\n<p style=\"text-align: justify;\">This is the way you could solve the problem in Haskell &#8211; Don&#8217;t run away just yet! I promise it will be quick and painless:<\/p>\n<pre class=\"lang:haskell decode:true\">import AnimalFarmLtd.AnimalManagement -- Will bring animal types from third party library\n\ndata PersonId = ... -- This is PersonId type definition\ndata ScheduledActivity = ... -- And ScheduledActivity...\ndata Date = ...\n\ndata Car = Car { brand :: String, model :: String } -- This is the type of car values\ndata Tractor = Tractor { brand :: String, model :: String, horsePower: Int } -- likewise for tractors.\n\n-- At this point we have already defined the types for cars, tractos and...\n-- we've brought the types for each kind of animal. You could create values of those types:\n\nlet babeThePig = Pig \"Babe\" -- A pig called Babe\nlet fordMustang = Car \"Ford\" \"Mustang\" \n\n-- We've values (like instances of animals an cars, but have not classified them)\n\nclass Maintainable a where \n  scheduleMaintainance :: a -&gt; PersonId -&gt; Date -&gt; ScheduledActivity\n\n-- Now, lets classify Car type as a Maintainable thing by providing an implementation for `scheduleMaintainance`\n\ninstance Maintainable Car where -- Here, the type Car gets classified as Maintainable\n    scheduleMaintainance carValue worker dateWhen = ...\n\ninstance Maintainable Animal where -- as Car, type Animal gets the `Maintenable` interface.\n    -- `scheduleMaintainance` is implemented as Animal's `takeCareOf` function\n    scheduleMaintainance = takeCareOf \n\n-- Henceforth, you'll be able to use pass `babeThePig` to `scheduleMaintainance`.<\/pre>\n<p style=\"text-align: justify;\">You don&#8217;t need\u00a0to understand the above code beyond the idea of\u00a0<strong>having a way to say that some types can be associated with a certain interface even after definition<\/strong>. Remember:<\/p>\n<p style=\"text-align: center;\"><strong><em>Type classes are classes of types (classes of classes in Scala), not classes of instances<\/em><\/strong><\/p>\n<p style=\"text-align: justify;\">Despite\u00a0Scala&#8217;s type system being\u00a0closer to Java&#8217;s than to Haskell&#8217;s, we can use our magical dark matter &#8211; yes, our implicit values and conversions &#8211; to build Type Classes.<\/p>\n<ul>\n<li style=\"text-align: justify;\"><strong>Step 1,<\/strong>\u00a0<strong>Untangling the classes hierarchy:\u00a0<\/strong>The above classes graph is simplified since we will break the hard-coded composition relation with\u00a0<em>Animal\u00a0<\/em>interface.<br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone\" src=\"http:\/\/i.imgur.com\/M4xtrNO.png\" width=\"687\" height=\"150\" \/><\/p>\n<pre class=\"lang:scala decode:true\">trait Equipment {\n  def fix(worker: PersonId, date: Date): ScheduledActivity\n}\n\ncase class Car() extends Equipment {\n  def fix(worker: PersonId, date: Date): ScheduledActivity = ???\n}\n\ncase class Fence() extends Equipment {\n  def fix(worker: PersonId, date: Date): ScheduledActivity = ???\n}\n\ncase class Tractor() extends Equipment {\n  def fix(worker: PersonId, date: Date): ScheduledActivity = ???\n}<\/pre>\n<\/li>\n<li style=\"text-align: left;\"><strong>Step 2, Declaring the type class<\/strong>\u00a0(<em>Maintainance<\/em>) and its interface as in\n<pre class=\"lang:haskell decode:true \" title=\"Type class in Haskell\">class Maintainable a where \n  scheduleMaintainance :: a -&gt; PersonId -&gt; Date -&gt; ScheduledActivity<\/pre>\n<p>Which, in Scala, is a\u00a0trait:<\/p>\n<pre class=\"lang:scala decode:true\">trait Maintainable[T] {\n  def scheduleMaintainance(x: T, worker: PersonId, date: Date): ScheduledActivity\n}<\/pre>\n<\/li>\n<li style=\"text-align: left;\"><strong>Step 3, Making classes part of the type class:<\/strong>\u00a0In a delayed fashion of course&#8230;\n<pre class=\"lang:scala decode:true\">implicit object InstanceMaintainableEquipment extends Maintainable[Equipment] {\n  def scheduleMaintainance(x: Equipment, worker: PersonId, date: Date): ScheduledActivity = x.fix(worker, date)\n} \/\/Henceforth, all Equipment instances are part of Maintainable type class\n\nimplicit object InstanceMaintainableAnimal extends Maintainable[Animal] {\n  def scheduleMaintainance(x: Animal, worker: PersonId, date: Date): ScheduledActivity = x.takeCareOf(worker, date)\n} \/\/Henceforth, all Animal instances are part of Maintainable type class<\/pre>\n<\/li>\n<li><strong>Step 4, Making use of type class interface<\/strong>\u00a0throught the implicit context:\n<pre class=\"lang:scala decode:true\">def manageMaintenanceTasks[T : Maintainable](pending: T): ScheduledActivity = {\n ...\n ...\n implicitly[Maintenable[T]].scheduleMaintainance(pending, ...)\n}<\/pre>\n<\/li>\n<\/ul>\n<p style=\"text-align: justify;\">And BOOM! There it is, a kind of Haskell type system embedded in Scala and you know&#8230; classes &#8211; of types &#8211; have always existed in Haskell.<\/p>\n<p style=\"text-align: justify;\">However, there is something not so cool about these kind of type classes\u00a0in which\u00a0you need to pass the instance to the operations. It is possible to push the limits of OOP into this realm thus enabling the lovely infix notation we always feel comfortable with. Thus applying what has been called &#8230;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"http:\/\/i.imgur.com\/dD1xKTH.png\" width=\"529\" height=\"263\" \/><\/p>\n<p>&#8230;\u00a0<a href=\"http:\/\/spray.io\/blog\/2012-12-13-the-magnet-pattern\/\" target=\"_blank\" rel=\"noopener\">which was first described on Spray&#8217;s development blog<\/a>.<\/p>\n<p style=\"text-align: justify;\">The latter article is so well written and so clearly explains the concept, that copying its ideas would be not only useless, but most probably misleading.<\/p>\n<p style=\"text-align: justify;\">There is little differences between the magnet pattern and the type classes pattern as described above: Both rely on implicit values to link types to their class, that is to a set of operations. There is, however, a\u00a0main difference which clearly sets both patterns apart:<\/p>\n<ul>\n<li style=\"text-align: justify;\">Type classes rely on implicit objects, that is: values of the type\u00a0<span class=\"lang:scala decode:true crayon-inline\">TypeClassClass[T]<\/span>\u00a0 \u00a0&#8211; Where T is the type to be associated to the type class &#8211;\u00a0thus enabling the type class of frozen operations through an implicit evidence within the implicit context.Another example of type\u00a0<a href=\"http:\/\/www.scala-lang.org\/api\/2.11.8\/#scala.math.Ordering\" target=\"_blank\" rel=\"noopener\">class is Scala is the<\/a>\u00a0<span class=\"lang:scala decode:true crayon-inline\">Ordering[T]<\/span>\u00a0<a href=\"http:\/\/www.scala-lang.org\/api\/2.11.8\/#scala.math.Ordering\">trait<\/a>:\n<pre class=\"lang:scala decode:true \">\/**\n  * This example os a modification of the one found at\n  * Scala's API reference:\n  * http:\/\/www.scala-lang.org\/api\/current\/#scala.math.Ordering\n  *\n **\/\nimport scala.util.Sorting\n\ncase class Person(name:String, age:Int)\nval people = Array(Person(\"bob\", 30), Person(\"ann\", 32), Person(\"carl\", 19))\n\n\/\/ sort by age: This'll be the actual implicit evidence for quickSort\nimplicit object AgeOrdering extends Ordering[Person] {\n  def compare(a:Person, b:Person) = a.age compare b.age\n}\n\nSorting.quickSort(people)<\/pre>\n<\/li>\n<li style=\"text-align: justify;\">With magnets, on the other hand, the operations are not fixed as they depend on value parametrization which leads to an object containing the implementation of the operation for that parametrization. This\u00a0implies\u00a0that magnets are not provided by implicit values accessed through implicit evidence but, otherwise, are implicit conversions from the operation parameters to the implementation. e.g:\n<pre class=\"lang:scala decode:true\">\/\/ Magnet trait, base of all implementation objects\ntrait MaintenableMagnet {\n    def apply(worker: PersonId, date: Date): ScheduledActivity\n}\n    \n\/\/ This is thre association of the type Equipment to the \n\/\/ magnet (or \"cool type class\")\nobject MaintenableEquipementOps {\n    implicit def scheduleMaintainance(x: Equipment): MaintenableMagnet = \n        new MaintenableMagnet {\n            def apply(worker: PersonId, date: Date): ScheduledActivity =\n                x.fix(worker, date)\n        }\n}<\/pre>\n<p>An\u00a0example of use:<\/p>\n<pre class=\"lang:scala decode:true\">import MaintenableEquipementOps._\n\nval myCar = Car()\n\ndef manageFarmElement(magnet: MaintenableMagnet): ScheduledActivity =\n    magnet(\"Tom\", \"2016-10-16\")\n\nmanageFarmElement(c)<\/pre>\n<\/li>\n<\/ul>\n<p style=\"text-align: justify;\">It is possible to fiddle with Haskell-like type classes and Magnet patterns in order to explore a vastly wide space\u00a0of variations between them.<\/p>\n<h2 style=\"text-align: justify;\">Other notorious Implicit Dimension citizens<\/h2>\n<p style=\"text-align: justify;\">This article is already &#8220;<a href=\"http:\/\/es.urbandictionary.com\/define.php?term=tl%3Bdr\" target=\"_blank\" rel=\"noopener\">TLDR<\/a>&#8221;\u00a0so let&#8217;s briefly\u00a0visit a couple of interesting implicit value\/conversion cases.<\/p>\n<h2 style=\"text-align: justify;\">Implicit classes &amp; Implicit object<\/h2>\n<p style=\"text-align: justify;\">When we were getting to know the Type Classes nuts and bolts we saw that a singleton object can be tagged as implicit:<\/p>\n<pre class=\"lang:scala decode:true \">trait T\n\nimplicit object ObjectEvidence extends T {\n  ...\n}<\/pre>\n<p style=\"text-align: justify;\">It seems pretty obvious that it is just a regular singleton object tagged as implicit and, therefore, becomes also an implicit value to be used as an actual value of any call to a function with an implicit formal parameter of type\u00a0<span class=\"lang:scala decode:true crayon-inline \">T<\/span>\u00a0:<\/p>\n<pre class=\"lang:scala decode:true \">def f(implicit v: T): Unit = ???\n\nf \/\/Will receive `ObjectEvidence` as an actual parameter for `v`<\/pre>\n<p style=\"text-align: justify;\">The reasoning applied to understand what implicit objects are, can be extended to implicit classes. Whereas singleton object constructors do not require any parameter and can be built straightaway &#8211; without providing any parameter. There is a special type of class, the type of classes whose constructor receives exactly one parameter, than can be regarded as an implicit conversion from that parameter to instances of themselves (of the classes):<\/p>\n<pre class=\"lang:scala decode:true \">implicit class SpinSpinSugar(x: String) {\n    def doSomething(times: Int): Unit =\n        println(\"call on my...\\n\"*times)\n}\n\n\"underground\" doSomething 10<\/pre>\n<p style=\"text-align: justify;\">Convenient to write DSL, isn&#8217;t it?<\/p>\n<h2 style=\"text-align: justify;\">Dangers and pitfalls<\/h2>\n<p style=\"text-align: justify;\">A regular matter\u00a0universe is full of perils, it seems reasonable to think that playing with the mysteries of dark matter will bring problems of its own&#8230;<\/p>\n<h2 style=\"text-align: justify;\">Multiple completions<\/h2>\n<p style=\"text-align: justify;\">When I read the words &#8220;<em>error: ambiguous implicit values<\/em>&#8221; I feel like Han Solo entering an asteroid field when trying to escape\u00a0from the empire&#8230;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"http:\/\/i.imgur.com\/tA1bSg4.jpg\" width=\"427\" height=\"323\" \/><\/p>\n<p style=\"text-align: justify;\">But there is not so much to fear. To solve this problem, at least in a quick and dirty way, is a piece of cake. It just means that a method is implicitly expecting a parameter of type, let&#8217;s say,\u00a0<span class=\"lang:scala decode:true crayon-inline \">T<\/span>\u00a0and the implicit context has more than one value of that type to fill the gap which leads to ambiguity&#8230; The compiler is politely telling us:\u00a0<em>Dear<span style=\"color: #000000;\">\u00a0developer,<\/span>\u00a0please, can you be a little more specific?<\/em><\/p>\n<p style=\"text-align: justify;\">The easiest solution to this problem is to explicitly provide an actual parameter of that type to the function call:<\/p>\n<pre class=\"lang:scala decode:true\">      \n      object ImplicitsA {\n        implicit val i: Int = 1\n      }\n      \n      object ImplicitsB {\n        implicit val j: Int = 2\n      }\n\n      def f(implicit x: Int): Unit = ???\n      \n      def main: Unit = {\n        \n        import ImplicitsA._\n        import ImplicitsB._\n        \n        \/\/f Problematic call\n        f(ImplicitsA.i) \/\/ Dirty solution \n      }\n      \n<\/pre>\n<p style=\"text-align: justify;\">But we are not despicable\u00a0<del>bounty<\/del>\u00a0bug hunters, are we? As Scala developers &amp; software engineers we should strive for clean solutions and to find the root of the problem. In this case, as in most similar cases, the implicit context gets populated with implicit values of the same type from different imports. Just removing one of them would be the wiser approach.<\/p>\n<p style=\"text-align: justify;\">By the way, tools and IDEs &#8211; such us\u00a0<a href=\"https:\/\/plugins.jetbrains.com\/plugin\/?id=1347\" target=\"_blank\" rel=\"noopener\">IntelliJ (with its Scala Plugin)<\/a>\u00a0&#8211; can help locate were the implicit values come from. In the case of the mentioned IDE, selecting the calling expression, the one receiving ambiguous implicit actual parameters, and using the key shortcut\u00a0<span class=\"lang:default decode:true crayon-inline \">CONTROL+SHIFT+P<\/span>\u00a0will show a floating window showing the part of the implicit context to be used by the expression and the source of its values.<\/p>\n<p style=\"text-align: justify;\">It may happen that we can&#8217;t get rid of one of the imports because it may contain other useful implicit values, in such\u00a0cases, the problematic values can be avoided by diverting their symbol import:<\/p>\n<pre class=\"lang:scala decode:true\">      object ImplicitsA {\n        implicit val i: Int = 1\n        implicit val s: String = \"HELLO DOLLY\"\n        \n      }\n\n      object ImplicitsB {\n        implicit val j: Int = 2\n      }\n\n      def f(implicit x: Int): Unit = ???\n      def g(implicit x: Int, y: String): Unit = println(x, y)\n\n      def main: Unit = {\n\n        import ImplicitsA.{i =&gt; _, _} \/\/This will import everything from A except 'i'\n        import ImplicitsB._\n\n        g \/\/ j, from ImplicitsB and s from ImplicitsA will be passed\n\n      }\n<\/pre>\n<h2><\/h2>\n<h2 style=\"text-align: justify;\">Recursive completions: What can be cooler than a run-time recursion Stack Overflow Error?<\/h2>\n<p style=\"text-align: justify;\">A recursion stack overflow error which you can&#8217;t see, of course!<br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignleft\" src=\"http:\/\/i.imgur.com\/KzLyGAC.gif\" width=\"235\" height=\"240\" \/><\/p>\n<p style=\"text-align: justify;\">To wrap this post up, let&#8217;s take a look at\u00a0my favorite error in the Scala ecosystem. We have all come across the run-time stack overflow errors when defining wrong stop conditions &#8211; or none at all &#8211;\u00a0<span class=\"lang:scala decode:true crayon-inline \">def soFarSoGood: Long = 1 + soFarSoGood<\/span>\u00a0.<\/p>\n<p style=\"text-align: justify;\">Well, there is a misuse of implicit completions which can lead to unexpected\u00a0crashes under similar circumstances: Implicit auto-completion.<\/p>\n<pre class=\"lang:scala decode:true \">case class A()\ncase class B()\n\nimplicit def a2b(a: A): B = a\n\nval b: B = A() \/\/BOOM!<\/pre>\n<p>Be aware of cross implicit conversions and&#8230;<\/p>\n<p style=\"text-align: center;\"><strong>Enjoy<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Conway&#8217;s Game of Life: You could hardly imagine a simpler set of rules to code on your computer and\u00a0you\u00a0wouldn&#8217;t expect any interesting result at all, but&#8230; behold the wonders of its hidden\u00a0might!<\/p>\n","protected":false},"author":1,"featured_media":927,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[686],"tags":[],"ppma_author":[795],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v22.9 (Yoast SEO v22.9) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>The Developer\u2019s Guide to Scala Implicit Values (Part II) - Stratio Blog<\/title>\n<meta name=\"description\" content=\"The Conway\u2019s Game of Life is an example of how a simple set of rules can produce amazing and totally unexpected results. What about implicit context rules?\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"The Developer\u2019s Guide to Scala Implicit Values (Part II)\" \/>\n<meta property=\"og:description\" content=\"The Conway\u2019s Game of Life is an example of how a simple set of rules can produce amazing and totally unexpected results. What about implicit context rules?\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\" \/>\n<meta property=\"og:site_name\" content=\"Stratio\" \/>\n<meta property=\"article:published_time\" content=\"2016-10-19T14:47:12+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-09-20T13:47:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"730\" \/>\n\t<meta property=\"og:image:height\" content=\"312\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Stratio\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@stratiobd\" \/>\n<meta name=\"twitter:site\" content=\"@stratiobd\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Stratio\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"20 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\"},\"author\":{\"name\":\"Stratio\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/d0377b199cd052b17e15c9ba44c45ab7\"},\"headline\":\"The Developer\u2019s Guide to Scala Implicit Values (Part II)\",\"datePublished\":\"2016-10-19T14:47:12+00:00\",\"dateModified\":\"2023-09-20T13:47:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\"},\"wordCount\":2825,\"publisher\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png\",\"articleSection\":[\"Product\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\",\"url\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\",\"name\":\"The Developer\u2019s Guide to Scala Implicit Values (Part II) - Stratio Blog\",\"isPartOf\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png\",\"datePublished\":\"2016-10-19T14:47:12+00:00\",\"dateModified\":\"2023-09-20T13:47:39+00:00\",\"description\":\"The Conway\u2019s Game of Life is an example of how a simple set of rules can produce amazing and totally unexpected results. What about implicit context rules?\",\"breadcrumb\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage\",\"url\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png\",\"contentUrl\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png\",\"width\":730,\"height\":312},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.stratio.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"The Developer\u2019s Guide to Scala Implicit Values (Part II)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#website\",\"url\":\"https:\/\/www.stratio.com\/blog\/\",\"name\":\"Stratio Blog\",\"description\":\"Corporate blog\",\"publisher\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.stratio.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#organization\",\"name\":\"Stratio\",\"url\":\"https:\/\/www.stratio.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/stratio.com\/blog\/wp-content\/uploads\/2020\/06\/stratio-web-logo-1.png\",\"contentUrl\":\"https:\/\/stratio.com\/blog\/wp-content\/uploads\/2020\/06\/stratio-web-logo-1.png\",\"width\":260,\"height\":55,\"caption\":\"Stratio\"},\"image\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/stratiobd\",\"https:\/\/es.linkedin.com\/company\/stratiobd\",\"https:\/\/www.youtube.com\/c\/StratioBD\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/d0377b199cd052b17e15c9ba44c45ab7\",\"name\":\"Stratio\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/image\/bb38888f58c2bb664646155f78ae6ccc\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/e3387ad00609f34a56d6796400eb8191?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/e3387ad00609f34a56d6796400eb8191?s=96&d=mm&r=g\",\"caption\":\"Stratio\"},\"description\":\"Stratio guides businesses on their journey through complete #DigitalTransformation with #BigData and #AI. Stratio works worldwide for large companies and multinationals in the sectors of banking, insurance, healthcare, telco, retail, energy and media.\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"The Developer\u2019s Guide to Scala Implicit Values (Part II) - Stratio Blog","description":"The Conway\u2019s Game of Life is an example of how a simple set of rules can produce amazing and totally unexpected results. What about implicit context rules?","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/","og_locale":"en_US","og_type":"article","og_title":"The Developer\u2019s Guide to Scala Implicit Values (Part II)","og_description":"The Conway\u2019s Game of Life is an example of how a simple set of rules can produce amazing and totally unexpected results. What about implicit context rules?","og_url":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/","og_site_name":"Stratio","article_published_time":"2016-10-19T14:47:12+00:00","article_modified_time":"2023-09-20T13:47:39+00:00","og_image":[{"width":730,"height":312,"url":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png","type":"image\/png"}],"author":"Stratio","twitter_card":"summary_large_image","twitter_creator":"@stratiobd","twitter_site":"@stratiobd","twitter_misc":{"Written by":"Stratio","Est. reading time":"20 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#article","isPartOf":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/"},"author":{"name":"Stratio","@id":"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/d0377b199cd052b17e15c9ba44c45ab7"},"headline":"The Developer\u2019s Guide to Scala Implicit Values (Part II)","datePublished":"2016-10-19T14:47:12+00:00","dateModified":"2023-09-20T13:47:39+00:00","mainEntityOfPage":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/"},"wordCount":2825,"publisher":{"@id":"https:\/\/www.stratio.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage"},"thumbnailUrl":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png","articleSection":["Product"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/","url":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/","name":"The Developer\u2019s Guide to Scala Implicit Values (Part II) - Stratio Blog","isPartOf":{"@id":"https:\/\/www.stratio.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage"},"image":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage"},"thumbnailUrl":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png","datePublished":"2016-10-19T14:47:12+00:00","dateModified":"2023-09-20T13:47:39+00:00","description":"The Conway\u2019s Game of Life is an example of how a simple set of rules can produce amazing and totally unexpected results. What about implicit context rules?","breadcrumb":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#primaryimage","url":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png","contentUrl":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/10\/Guide_part2.png","width":730,"height":312},{"@type":"BreadcrumbList","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.stratio.com\/blog\/"},{"@type":"ListItem","position":2,"name":"The Developer\u2019s Guide to Scala Implicit Values (Part II)"}]},{"@type":"WebSite","@id":"https:\/\/www.stratio.com\/blog\/#website","url":"https:\/\/www.stratio.com\/blog\/","name":"Stratio Blog","description":"Corporate blog","publisher":{"@id":"https:\/\/www.stratio.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.stratio.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.stratio.com\/blog\/#organization","name":"Stratio","url":"https:\/\/www.stratio.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.stratio.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/stratio.com\/blog\/wp-content\/uploads\/2020\/06\/stratio-web-logo-1.png","contentUrl":"https:\/\/stratio.com\/blog\/wp-content\/uploads\/2020\/06\/stratio-web-logo-1.png","width":260,"height":55,"caption":"Stratio"},"image":{"@id":"https:\/\/www.stratio.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/stratiobd","https:\/\/es.linkedin.com\/company\/stratiobd","https:\/\/www.youtube.com\/c\/StratioBD"]},{"@type":"Person","@id":"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/d0377b199cd052b17e15c9ba44c45ab7","name":"Stratio","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/image\/bb38888f58c2bb664646155f78ae6ccc","url":"https:\/\/secure.gravatar.com\/avatar\/e3387ad00609f34a56d6796400eb8191?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/e3387ad00609f34a56d6796400eb8191?s=96&d=mm&r=g","caption":"Stratio"},"description":"Stratio guides businesses on their journey through complete #DigitalTransformation with #BigData and #AI. Stratio works worldwide for large companies and multinationals in the sectors of banking, insurance, healthcare, telco, retail, energy and media."}]}},"authors":[{"term_id":795,"user_id":1,"is_guest":0,"slug":"stratioadmin","display_name":"Stratio","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/e3387ad00609f34a56d6796400eb8191?s=96&d=mm&r=g","0":null,"1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":""}],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/posts\/791"}],"collection":[{"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/comments?post=791"}],"version-history":[{"count":12,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/posts\/791\/revisions"}],"predecessor-version":[{"id":13939,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/posts\/791\/revisions\/13939"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/media\/927"}],"wp:attachment":[{"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/media?parent=791"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/categories?post=791"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/tags?post=791"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=791"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}