{"id":737,"date":"2016-05-23T13:44:11","date_gmt":"2016-05-23T13:44:11","guid":{"rendered":"http:\/\/blog.stratio.com\/?p=737"},"modified":"2023-09-20T13:44:34","modified_gmt":"2023-09-20T13:44:34","slug":"developers-guide-scala-implicit-values-part-1","status":"publish","type":"post","link":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/","title":{"rendered":"The Developer\u2019s Guide to Scala Implicit Values (Part I)"},"content":{"rendered":"<p>Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026<!--more--><\/p>\n<p style=\"text-align: justify;\">When used correctly,\u00a0they reduce the verbosity of Scala programs thus providing\u00a0easy to read code. But their most important feature is that they offer\u00a0a way to make your libraries functionality extendible without having to change their code nor needing\u00a0to distribute\u00a0it.<\/p>\n<p style=\"text-align: justify;\"><img loading=\"lazy\" decoding=\"async\" class=\" alignleft\" src=\"http:\/\/static.giantbomb.com\/uploads\/original\/1\/18723\/1839615-dont_panic_thumb.jpg\" alt=\"\" width=\"300\" height=\"300\" \/>A great power comes with a great responsibility however. For new comers, as well as for relatively experienced Scala users, they can become a galaxy of confusions and pitfalls derived from the fact that the use of implicit values imply the compiler making decisions not obviously described in the code and following a set of rules with some unexpected results.<\/p>\n<p style=\"text-align: justify;\">This post pretends to shed some light on the use of implicit values. Its\u00a0content isn\u2019t 100% original, it is just a tourist guide through this full of marvels, and sometimes dangerous, code jungle.<br \/>\nAs most of those monstrous things that make us shiver, implicit values are mostly harmless once you get to know them.<\/p>\n<h2>Meeting the implicit family: Implicit Parameters and Implicit Conversions<\/h2>\n<p style=\"text-align: justify;\">In essence, implicit values are no more than a tool for\u00a0providing the compiler with a way to continue when the code it is\u00a0compiling lacks some elements which should had been explicitly specified. These elements can only be:<\/p>\n<ul style=\"text-align: justify;\">\n<li>A conversion of an element from a type (T) to another (S) when the element is used in a place where a S is required.<\/li>\n<li>An actual parameter (value passed to a function in a function call).<\/li>\n<\/ul>\n<p style=\"text-align: justify;\">And are fulfilled with those implicit values present in the context of the incomplete code.<br \/>\nTherefore,\u00a0there\u00a0is one type of implicit value for each kind of element above:\u00a0<strong>Implicit conversions<\/strong>\u00a0and\u00a0<strong>implicit parameters<\/strong>.<\/p>\n<h2 style=\"text-align: justify;\"><\/h2>\n<h2>The goal of implicit conversions<\/h2>\n<p style=\"text-align: justify;\">The straight line is the shortest path from one point to another, similarly the shortest path from a type to another is a function. What is then the most obvious Scala language tool to describe conversions from a type to another?<\/p>\n<p style=\"text-align: justify;\">Yes, functions! A conversion is just a function from T to S<\/p>\n<pre class=\"\">def\u00a0conversion(x:\u00a0T):\u00a0S\u00a0=\u00a0???<\/pre>\n<p style=\"text-align: justify;\">Ok, but just defining a function doesn\u2019t imply that all places where S is expected will be also be able to receive a parameter of type T. Let\u2019s solve that:<\/p>\n<div style=\"text-align: justify;\">\n<pre id=\"highlighter_277304\" class=\"syntaxhighlighter nogutter notranslate scala\">implicit\u00a0def\u00a0conversion(x:\u00a0T):\u00a0S\u00a0=\u00a0???<\/pre>\n<\/div>\n<p style=\"text-align: justify;\">Making the definition as\u00a0<strong>implicit\u00a0<\/strong>tells the compiler that it should try to apply\u00a0<em>conversion\u00a0<\/em>when S is expected but T is passed.<\/p>\n<p style=\"text-align: justify;\">The provided type is known as the conversion\u00a0<strong>source\u00a0<\/strong>and the type the conversion provides is the\u00a0<strong>target<\/strong>.<\/p>\n<pre class=\"\">\u00a0\ncase\u00a0class\u00a0A(x:\u00a0Int)\ncase\u00a0class\u00a0B(m:\u00a0String, v:\u00a0Double) {\n\u00a0def\u00a0method\u00a0=\u00a0println(s\"hello world $m $v\")\n}\n\u00a0\nval\u00a0a\u00a0=\u00a0A(10)\nvar\u00a0b:\u00a0B\u00a0=\u00a0B(\"what is the meaning of life?\",\u00a042.0)<\/pre>\n<p style=\"text-align: justify;\">It is obvious that trying something like:<\/p>\n<pre class=\"\">b = a<\/pre>\n<p style=\"text-align: justify;\">Won\u2019t even compile because a type mismatch. However, once an implicit conversion from A (<strong>source<\/strong>) to B (<strong>target<\/strong>) is available (in context; Don\u2019t worry, this concept will be explained soon), the compiler will try to apply it in order to fix the type error:<\/p>\n<pre class=\"\">implicit def conv(v: A): B = B(\"Some String\", v.x.toDouble)\n\u00a0\nb = a\u00a0\/\/Now, this is equivalent to write\nb = conv(a)\u00a0\/\/ so it works! (A is the source type and B the target)<\/pre>\n<div style=\"text-align: justify;\">\n<div class=\"toolbar\">\u00a0This also applies to attribute accesses as well as method calls:<\/div>\n<\/div>\n<pre class=\"\">Double dval\u00a0=\u00a0a.v\u00a0\/\/ A doesn't have a v attribute, but B does...\n\/\/ so it is translated to: Double dval = conv(a).v\nString m\u00a0=\u00a0a.m\u00a0\/\/ m = conv(a).m\na.method\u00a0\/\/ conv(a).method<\/pre>\n<p style=\"text-align: justify;\">Finally, A elements become also valid actual parameters for formal parameters of type B:<\/p>\n<pre class=\"\">def\u00a0f(x:\u00a0B):\u00a0Double\u00a0=\u00a0x.m.size * x.v\nf(a)\u00a0==\u00a0f(conv(a))<\/pre>\n<table width=\"585\" cellspacing=\"0\" cellpadding=\"4\">\n<colgroup>\n<col width=\"256*\" \/><\/colgroup>\n<tbody>\n<tr>\n<td><strong>Rule of thumb<\/strong>\u00a0Given a context containing an implicit conversion from T to S, you can\u00a0use any element of type T (<strong>source type<\/strong>) as if it were of type S (<strong>target type<\/strong>).<\/td>\n<\/tr>\n<tr>\n<td valign=\"top\" width=\"100%\"><strong>Warning<\/strong>\u00a0Keep in mind that this rule does NOT mean that objects of type T will be also seen as elements of type S but that the corresponding conversion (implemented as a function from T to S) will be applied.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>And implicit parameters\u2019s?<\/p>\n<p style=\"text-align: justify;\">The concept behind implicit parameters is simple: A method (or function) parameter which can be omitted when calling the method.<\/p>\n<p style=\"text-align: justify;\">As any Scala developer should know, it allows the declaration of functions or methods with 0, 1 or more than 1\u00a0parameter lists (this last case is, in fact, the way the language enables\u00a0<a href=\"http:\/\/www.uncarved.com\/blog\/not_currying.mrk\">currying<\/a>). Any function implicit parameter must be in the last parameter list and this list must be marked as implicit. Any parameter within this list will be therefore considered implicit which means that can be potentially provided by an implicit value within the function call context (again this term! It\u2019s claiming its own sub-section here!)<\/p>\n<p style=\"text-align: justify;\">Lets see this in action:<\/p>\n<pre class=\"\">\u00a0\ndef\u00a0f(implicit\u00a0x:\u00a0Int)\u00a0=\u00a0x*2\n\u00a0\n\/\/f can be used as any other function ...\nval\u00a0res\u00a0=\u00a0f(42)\u00a0\u00a0\u00a0\/\/.. and receive\u00a0 'x' explicitly\n\u00a0\n\/\/Or, with an implicit 'Int' in context, ...\nimplicit\u00a0val\u00a0v:\u00a0Int\u00a0=\u00a042\u00a0\/\/Implicit value (implicit actual param)\n\u00a0\n\/\/ Be called without any actual parameter:\nval\u00a0resb\u00a0=\u00a0f<\/pre>\n<div style=\"text-align: justify;\">As you may have already deduced, regular parameter lists can be present along with implicit parameter list:<\/div>\n<div style=\"text-align: justify;\"><\/div>\n<pre class=\"\">def\u00a0g(x:\u00a0Int, y:\u00a0Int)(implicit\u00a0base:\u00a0Int):\u00a0Int\u00a0=\u00a0(x+y)%base\n\u00a0\ng(41,1)\u00a0\/\/Will return 0, (41+1)%42, but ...\ng(41,1)(100)\/\/will return 42 because of the higher value for 'base'<\/pre>\n<p style=\"text-align: justify;\">Implicit values are hugely used to express contexts. e.g:<br \/>\n<em>In a physics simulator for different planets,\u00a0wouldn\u2019t it be uncomfortable having to explicitly pass the gravitational constant to each calculation method? Why not make it an implicit parameter with a value when working on Earth an another when working on Mars?<\/em>\u00a0This observation drives to to concept of\u00a0<strong>implicit context<\/strong>, again!<\/p>\n<p style=\"text-align: justify;\">It is worth of mentioning that the compiler will try those implicit actual parameters (implicit values) which are\u00a0<strong>of the same type than the one required by the formal parameter.\u00a0<\/strong>The value identifier, its name in the program, doesn\u2019t make any different for the compiler, however it is desirable to\u00a0follow the same naming\u00a0rules than any other identifier.<\/p>\n<h2 style=\"text-align: justify;\">Implicit Conversions and Implicit Parameters: Two sides of the same coin<\/h2>\n<p style=\"text-align: justify;\">Before throwing ourselves into the sea of the implicit context, it would be nice to make an stop and think about the relation between the two, so seemingly\u00a0different, implicit tools.<\/p>\n<p style=\"text-align: justify;\">Being Scala a language with such a functional programming load, \u00a0its functions\u00a0can be considered\u00a0values. \u00a0We have also seen that implicit conversions are functions marked implicit. Following this reasoning one could try to write an implicit conversion as follows:<\/p>\n<pre class=\"\">case\u00a0class\u00a0B(x:\u00a0Int)\ncase\u00a0class\u00a0A(x:\u00a0String)\n\u00a0\nimplicit\u00a0val\u00a0a2b\u00a0\u00a0=\u00a0(v:\u00a0A)\u00a0=&gt; B(v.x.toInt)\n\u00a0\nval\u00a0b:\u00a0B\u00a0=\u00a0A(\"12\")<\/pre>\n<p style=\"text-align: justify;\">And, as expected, that would work.\u00a0<strong>Implicit conversions are functions, therefore values.<\/strong><\/p>\n<p style=\"text-align: justify;\">On the other hand,\u00a0<strong>actual implicit parameters<\/strong>\u00a0(the ones used to complete incomplete function calls)\u00a0<strong>are just that: values<\/strong>.<\/p>\n<p style=\"text-align: justify;\"><img loading=\"lazy\" decoding=\"async\" class=\" wp-image-13231 aligncenter\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/coins.png\" alt=\"\" width=\"517\" height=\"272\" \/><\/p>\n<p style=\"text-align: justify;\">So, at the end of the day, we have that both implicit conversions and implicit actual parameters\u00a0are values, special values so marked by the\u00a0<em>implicit<\/em>\u00a0keyword. This should be the first clue to understand the concept of implicit context.<\/p>\n<h2><\/h2>\n<h2>Context?<\/h2>\n<p style=\"text-align: justify;\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-13232 alignleft\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/etta-james-copy-150x150.jpg\" alt=\"\" width=\"150\" height=\"150\" \/><\/p>\n<p style=\"text-align: justify;\">At last! Lest\u2019s talk about the\u00a0<del>in<\/del>famous implicit context. Last section ended providing some insight on what may be this concept so many times referenced in this post.<\/p>\n<p style=\"text-align: justify;\">The<strong>\u00a0implicit context\u00a0<\/strong>at a given point of your source code is the set of implicit values available for the compiler to perform type conversions or complete function calls when that point of code is providing an unexpected type object\u00a0or missing some parameter in a function call.<\/p>\n<p style=\"text-align: justify;\">The same way the Hitchhiker\u2019s Guide to the Galaxy describes a\u00a0<a href=\"http:\/\/hitchhikers.wikia.com\/wiki\/Towel\">towel<\/a>\u00a0as\u00a0\u2026\u00a0<em>the most massively useful thing an interstellar hitch hiker can have \u2026 \u2013\u00a0<\/em>an item\u00a0you should under no circumstances loose \u2013 the knowledge of your current implicit context is the most important think to keep in mind when developing and working with code which uses\u00a0implicit values.<\/p>\n<table cellspacing=\"0\" cellpadding=\"4\">\n<colgroup>\n<col width=\"256*\" \/><\/colgroup>\n<tbody>\n<tr>\n<td><strong>Rule of thumb<\/strong>\u00a0The implicit context is a\u00a0satchel\u00a0of values on which the compiler may look for a fitting piece for those gaps generated by the lack of an actual parameter or a type mismatch. The contents of this satchel\u00a0may be different at different points of your code, that is: Different contexts at different places on your code.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p style=\"text-align: justify;\">At a given point the implicit context is determined by a fairly\u00a0concrete set of rules. Instead enumerating all of them here (for that you can always use Google for that), I\u2019ll try to give a guide to understand what implicit values are available at each moment.<\/p>\n<p style=\"text-align: justify;\">All implicit values (both conversions and actual parameters) which are declared in the same scope than a given code snippet are available for the compiler to complete what it my by missing in that snippet<\/p>\n<p style=\"text-align: justify;\">The easiest way of understanding this affirmation is by visualizing implicit elements as regular mutable or immutable variables. If you understand the rules governing the following example:<\/p>\n<pre class=\"\">{\n\u00a0val\u00a0x\u00a0=\u00a03\n\u00a0var\u00a0y\u00a0=\u00a040;\n\u00a0{\n\u00a0\u00a0val\u00a0x\u00a0=\u00a07\n\u00a0\u00a0y\u00a0=\u00a042\n\u00a0\u00a0println(x*y)\n\u00a0}\n\u00a0println(x*y)\n}\n\/\/Printing:\n\/\/ 294\n\/\/ 126<\/pre>\n<div style=\"text-align: justify;\">\u00a0Then probably know the variable scopes in Scala, therefore you also understand how implicit context evolves in its more general case, and thus, in many practical cases.\u00a0Understanding this example should be a piece of cake for you:<\/div>\n<div style=\"text-align: justify;\">\n<div id=\"highlighter_121405\" class=\"syntaxhighlighter nogutter notranslate scala\">\n<div class=\"toolbar\">\n<pre class=\"\">def\u00a0f(implicit\u00a0a:\u00a0Int, b:\u00a0String):\u00a0Unit\u00a0=\u00a0println(s\"a=$a\\tb=$b\")<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<p>This function is defined in the same scope than the following block:<\/p>\n<pre class=\"\">{\n\u00a0implicit\u00a0val\u00a0x:\u00a0Int\u00a0=\u00a03;\u00a0\/\/Implicit value of type Int\n\u00a0implicit\u00a0val\u00a0y:\u00a0String\u00a0=\u00a0\"humans\";\u00a0\/* This implicit value will be\n\u00a0available at this scope level as well as at any sub-level *\/\n\u00a0{\n\u00a0\u00a0f;\u00a0\/\/The implicit actual parameter for strings here is \"humans\"\n\u00a0\u00a0{\n\u00a0\u00a0\u00a0\/\/But this implicit declaration for strings eclipses the latter\n\u00a0\u00a0\u00a0implicit\u00a0val\u00a0y:\u00a0String\u00a0=\u00a0\"dolphins\";\n\u00a0\u00a0\u00a0f\n\u00a0\u00a0}\n\u00a0}\n\u00a0f\n}<\/pre>\n<div style=\"text-align: justify;\">\n<div id=\"highlighter_192767\" class=\"syntaxhighlighter nogutter notranslate scala\">\n<div class=\"toolbar\">\u00a0The output for the snippet above is:<\/div>\n<div>\n<pre class=\"\">a=3 b=humans\na=3 b=dolphins\na=3 b=humans<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<ul style=\"text-align: justify;\">\n<li style=\"text-align: justify;\">The first line corresponds to the first call being performed at depth 1. At that point, implicit values\u00a0<em>x<\/em>\u00a0and\u00a0<em>y\u00a0<\/em>are in the implicit context as they are declared at depth 0.<\/li>\n<li style=\"text-align: justify;\">The second is printed by the call at depth 2. The implicit context in this level has changed, the value \u201chumans\u201d for \u00a0<em>y\u00a0<\/em>has been hidden by a new one which will be only available at this scope since it has not more sub-levels.<\/li>\n<li style=\"text-align: justify;\">Therefore, the last call will print \u201chumans\u201d again, the scope here is the one for level 0.<\/li>\n<\/ul>\n<p style=\"text-align: justify;\">Yes, \u00a0I said the compiler wouldn\u2019t consider the identifier as a criteria for picking implicit values. Then, why has the implicit value at level 2 the same value as at level 0? Easy, if both identifiers were different they then the implicit context at level 2 would contain two different values for strings. Precisely because the compiler doesn\u2019t take into consideration the implicit identifiers for picking the gap fillers,\u00a0it wouldn\u2019t know which of them use:<\/p>\n<div style=\"text-align: justify;\">\n<pre id=\"highlighter_194841\" class=\"syntaxhighlighter nogutter notranslate scala\">{\n\u00a0implicit\u00a0val\u00a0x:\u00a0Int\u00a0=\u00a03;\u00a0\/\/Implicit value of type Int\n\u00a0implicit\u00a0val\u00a0y:\u00a0String\u00a0=\u00a0\"humans\";\u00a0\/* This implicit value will be\n\u00a0available at this scope level as well as at any sub-level *\/\n\u00a0{\n\u00a0\u00a0f;\u00a0\/\/The implicit actual parameter for strings here is \"humans\"\n\u00a0\u00a0{\n\u00a0\u00a0\u00a0implicit\u00a0val\u00a0z:\u00a0String\u00a0=\u00a0\"dolphins\";\n\u00a0\u00a0\u00a0\/* The implicit context at this point contains 2\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0implicit values of type String because they are in scope\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0with different identifiers.\n\u00a0\u00a0\u00a0*\/\n\u00a0\u00a0\u00a0f\n\u00a0\u00a0}\n\u00a0}\n\u00a0f\n}<\/pre>\n<\/div>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone  wp-image-13234\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/freeman-dent2-1024x684.jpg\" alt=\"\" width=\"791\" height=\"528\" \/><\/p>\n<div style=\"text-align: justify;\">\n<pre id=\"highlighter_332617\" class=\"syntaxhighlighter nogutter notranslate bash\">: error: ambiguous implicit values:\n\u00a0both value z of\u00a0type\u00a0String\n\u00a0and value y of\u00a0type\u00a0String\n\u00a0match expected\u00a0type\u00a0String<\/pre>\n<\/div>\n<table cellspacing=\"0\" cellpadding=\"4\">\n<colgroup>\n<col width=\"256*\" \/><\/colgroup>\n<tbody>\n<tr>\n<td><strong>Warning<\/strong>\u00a0The chosen names for implicit values are important after all! The compiler wouldn\u2019t choose which one use upon they identifier name. However,\u00a0values declared at one scope can hide other\u00a0values with the same name declared at upper scope levels.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p style=\"text-align: justify;\">This is just an example for implicit parameters but the same ruling pattern applies for implicit conversions. So far, implicit parameters behave the same way implicit conversions do. Let\u2019s explore their differences.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-13235 alignleft\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/implicit_param.png\" alt=\"\" width=\"216\" height=\"282\" \/><\/p>\n<p style=\"text-align: justify;\">Formal\u00a0<strong>implicit parameters<\/strong>\u00a0become implicit values within the function body<\/p>\n<p style=\"text-align: justify;\">Any parameter in a function implicit parameter list is an implicit value in the scope of the function body. It doesn\u2019t matter whether the actual parameter has been filled by the compiler or explicitly passed. As long as it was declared within the implicit parameter list, it will be implicit within the function scope.<\/p>\n<p style=\"text-align: justify;\">For the following examples, consider the function below:<\/p>\n<div style=\"text-align: justify;\">\n<pre id=\"highlighter_915001\" class=\"syntaxhighlighter nogutter notranslate scala\">def\u00a0implicitly[T](implicit\u00a0e:\u00a0T)\u00a0=\u00a0e<\/pre>\n<\/div>\n<p style=\"text-align: justify;\">It expects a parameter of the parametrized type and use it as its return value. This kind of function is useful to \u201ccapture\u201d implicit values references and make them explicit references. That isn\u2019t only useful for debugging purposes but also increases the scalability of your code. e.g:<\/p>\n<ul style=\"text-align: justify;\">\n<li>What if you need to pass your implicit physics simulation engine\u00a0context to a method for which that context parameter isn\u2019t declared as implicit?<\/li>\n<li>What if you are using Java libraries?<\/li>\n<li>What is the easiest way to check how an implicit value is being resolved?<\/li>\n<\/ul>\n<p style=\"text-align: justify;\">This function importance is such that it is included within Scala\u2019s\u00a0<em>Predef<\/em>\u00a0object.<\/p>\n<p style=\"text-align: justify;\">Knowing the existence of\u00a0<em>implicitly\u00a0<\/em>when can now use it at the promised examples:<\/p>\n<pre class=\"\">def\u00a0f(implicit\u00a0x:\u00a0Int)\u00a0=\u00a0println(\n\u00a0\u00a0s\"Implicit value for integers within f's body: ${implicitly[Int]}\"\n)\n\u00a0\nf(3)\u00a0\/* Despite 3 being explicitly passed to f,\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0it is an implicit value within f's body *\/\n\u00a0\nimplicit\u00a0val\u00a0vOutsideF\u00a0=\u00a042\nf\u00a0\/* Obviously, that's also true when the actual parameter is\n\u00a0\u00a0\u00a0\u00a0\u00a0filled by the compiler. *\/<\/pre>\n<div style=\"text-align: justify;\"><\/div>\n<p><strong>Implicit conversions<\/strong>\u00a0defined at a target class\u00a0companion object are available for the compiler to use source\u00a0\u2018s instances where target\u2019s are expected<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-13236 aligncenter\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/implicit_convs_target.png\" alt=\"\" width=\"281\" height=\"259\" \/><\/p>\n<p>When the compiler finds\u00a0a type mismatch it will not only try to apply implicit conversions in scope but also those defined in the companion object of the expected type\u00a0(<strong>target\u00a0type<\/strong>) class:<\/p>\n<pre class=\"\">case\u00a0class\u00a0A(x:\u00a0Int)\n\u00a0\ncase\u00a0class\u00a0B(x:\u00a0Double)\n\u00a0\nobject\u00a0B {\u00a0\/\/B class companion object\n\u00a0\u00a0implicit\u00a0def\u00a0fromA(o:\u00a0A):\u00a0B\u00a0=\u00a0B(o.x.toDouble)\n}\n\u00a0\nval\u00a0b:\u00a0B\u00a0=\u00a0A(3)\u00a0\/\/B is the target class\n\u00a0\n\/\/B, formal parameter class, is the target class\ndef\u00a0show(x:\u00a0B)\u00a0=\u00a0println(x)\nshow(A(42))<\/pre>\n<p><strong>Implicit conversions<\/strong>\u00a0defined at a source\u00a0class companion object are available for the compiler to use source\u2019s instances where target\u2019s are expected<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-13237 aligncenter\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/implicit_conv_source.png\" alt=\"\" width=\"277\" height=\"259\" \/><\/p>\n<p>Likewise the case above, the compiler will also try implicit conversions defined in the companion object of the passed instance\u00a0class (<strong>source class<\/strong>).<\/p>\n<pre class=\"\">case\u00a0class\u00a0A(x:\u00a0Int)\ncase\u00a0class\u00a0B(x:\u00a0Double)\n\u00a0\nobject\u00a0A {\u00a0\/\/A class companion object\n\u00a0\u00a0implicit\u00a0def\u00a0toB(o:\u00a0A):\u00a0B\u00a0=\u00a0B(o.x.toDouble)\n}\n\u00a0\nval\u00a0b:\u00a0B\u00a0=\u00a0A(3)\u00a0\/\/B is the target class\n\u00a0\n\/\/B, formal parameter class, is the target class\ndef\u00a0show(x:\u00a0B)\u00a0=\u00a0println(x)\nshow(A(42))<\/pre>\n<p>This subspace of the implicit context\u00a0is great for expanding old libraries without modifying their source code since it allows you to make your own types compatible with them\u00a0by just adding the convenient implicit conversions in your classes companion objects.<\/p>\n<p>Mapping your Scala developer\u2019s adventure satchel<\/p>\n<p>Yes, your implicit context is a big satchel. So far we have been exploring its pockets so it seems a good a idea to have its image as a whole:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-13238 aligncenter\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/implicit_convs_map.png\" alt=\"\" width=\"342\" height=\"303\" \/><\/p>\n<p style=\"text-align: justify;\">It ins\u2019t that the scope is more important than any other implicit context part but it is drawn a little bit bigger because of its dynamism: It can mutate at any time by the means of new declarations of the use of\u00a0<em>import<\/em>.<\/p>\n<p style=\"text-align: justify;\">This is just a simplification of the principles determining the current implicit context at a Scala program point. These principles can interoperate resulting in not so intuitive effects. I find one \u00a0them particularly interesting because it highlights the nature of implicit parameters and conversions as different flavours of the same concept:<strong>\u00a0Implicit value<\/strong>.<\/p>\n<p>Consider the following pair of functions:<\/p>\n<div style=\"text-align: justify;\">\n<div id=\"highlighter_156679\" class=\"syntaxhighlighter nogutter notranslate scala\">\n<pre class=\"\">def\u00a0show(x:\u00a0B)\u00a0=\u00a0println(x)\u00a0\/\/Expects B instances\n\ndef\u00a0f(x:\u00a0A)(implicit\u00a0a2b:\u00a0A\u00a0=&gt; B)\u00a0=\u00a0show(x)\u00a0\/\/Receives A instances<\/pre>\n<\/div>\n<\/div>\n<p>It may result strange that the code above compiles and even more so that the following snippet works:<\/p>\n<pre class=\"\">f(A(42))( v\u00a0=&gt; B(v.x.toDouble))<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-13239 alignleft\" src=\"http:\/\/blog.stratio.com\/wp-content\/uploads\/2016\/05\/fordperfect-300x214.png\" alt=\"\" width=\"300\" height=\"214\" \/><\/p>\n<p style=\"text-align: justify;\">But there is no magic here once we analyse what the\u00a0<em>a2b\u00a0<\/em>parameter is: It is of the type\u00a0<em>A=&gt;B\u00a0<\/em>which means that it is a function from\u00a0<em>A\u00a0<\/em>to\u00a0<i>B,\u00a0<\/i>the same type an implicit conversion for these types would be. On the other hand, it is an implicit parameter and that implies\u00a0<em>a2b\u00a0<\/em>to be marked as\u00a0<em>implicit\u00a0<\/em>within\u00a0<em>f\u00a0<\/em>body. Both the type and the mark as implicit are the ingredients for an implicit conversion so when the call to\u00a0<em>show\u00a0<\/em>expects a\u00a0<em>B\u00a0<\/em>instance the compiler will be able to use the awkwardly\u00a0declared implicit conversion\u00a0<em>a2b<\/em>.<\/p>\n<h2>To be continued\u2026<\/h2>\n<p style=\"text-align: justify;\">So far we have reviewed the basis of implicit parameters and conversions. This is like describing what roads and cars are and how the work but not talking about how to exploit them by asking good intentioned people to drive you to your destination in exchange of contemplating your shiny and friendly thumb.<\/p>\n<p style=\"text-align: justify;\">The next part (hopefully posted soon) will explain how to utilize these powerful tools in a higher level of abstraction as well as warning you of the dangerous singularities and pitfalls you may encounter in their use.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Implicit parameters and conversions are powerful tools in Scala increasingly\u00a0used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026 When used correctly,\u00a0they reduce the verbosity of Scala programs thus providing\u00a0easy to read code.<\/p>\n","protected":false},"author":1,"featured_media":739,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[686],"tags":[85],"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 I) - Stratio Blog<\/title>\n<meta name=\"description\" content=\"Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026\" \/>\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-1\/\" \/>\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 I)\" \/>\n<meta property=\"og:description\" content=\"Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/\" \/>\n<meta property=\"og:site_name\" content=\"Stratio\" \/>\n<meta property=\"article:published_time\" content=\"2016-05-23T13:44:11+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-09-20T13:44:34+00:00\" \/>\n<meta name=\"author\" content=\"Stratio\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:image\" content=\"http:\/\/UploadImage\" \/>\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=\"15 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-1\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/\"},\"author\":{\"name\":\"Stratio\",\"@id\":\"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/d0377b199cd052b17e15c9ba44c45ab7\"},\"headline\":\"The Developer\u2019s Guide to Scala Implicit Values (Part I)\",\"datePublished\":\"2016-05-23T13:44:11+00:00\",\"dateModified\":\"2023-09-20T13:44:34+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/\"},\"wordCount\":2303,\"publisher\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png\",\"keywords\":[\"spark\"],\"articleSection\":[\"Product\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/\",\"url\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/\",\"name\":\"The Developer\u2019s Guide to Scala Implicit Values (Part I) - Stratio Blog\",\"isPartOf\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png\",\"datePublished\":\"2016-05-23T13:44:11+00:00\",\"dateModified\":\"2023-09-20T13:44:34+00:00\",\"description\":\"Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026\",\"breadcrumb\":{\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage\",\"url\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png\",\"contentUrl\":\"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png\",\"width\":730,\"height\":312},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#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 I)\"}]},{\"@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 I) - Stratio Blog","description":"Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026","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-1\/","og_locale":"en_US","og_type":"article","og_title":"The Developer\u2019s Guide to Scala Implicit Values (Part I)","og_description":"Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026","og_url":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/","og_site_name":"Stratio","article_published_time":"2016-05-23T13:44:11+00:00","article_modified_time":"2023-09-20T13:44:34+00:00","author":"Stratio","twitter_card":"summary_large_image","twitter_image":"http:\/\/UploadImage","twitter_creator":"@stratiobd","twitter_site":"@stratiobd","twitter_misc":{"Written by":"Stratio","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#article","isPartOf":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/"},"author":{"name":"Stratio","@id":"https:\/\/www.stratio.com\/blog\/#\/schema\/person\/d0377b199cd052b17e15c9ba44c45ab7"},"headline":"The Developer\u2019s Guide to Scala Implicit Values (Part I)","datePublished":"2016-05-23T13:44:11+00:00","dateModified":"2023-09-20T13:44:34+00:00","mainEntityOfPage":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/"},"wordCount":2303,"publisher":{"@id":"https:\/\/www.stratio.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage"},"thumbnailUrl":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png","keywords":["spark"],"articleSection":["Product"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/","url":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/","name":"The Developer\u2019s Guide to Scala Implicit Values (Part I) - Stratio Blog","isPartOf":{"@id":"https:\/\/www.stratio.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage"},"image":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage"},"thumbnailUrl":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png","datePublished":"2016-05-23T13:44:11+00:00","dateModified":"2023-09-20T13:44:34+00:00","description":"Implicit parameters and conversions are powerful tools in Scala increasingly used to develop concise, versatile tools such as DSLs, APIs, libraries\u2026","breadcrumb":{"@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#primaryimage","url":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png","contentUrl":"https:\/\/www.stratio.com\/blog\/wp-content\/uploads\/2016\/05\/Guide_3.png","width":730,"height":312},{"@type":"BreadcrumbList","@id":"https:\/\/www.stratio.com\/blog\/developers-guide-scala-implicit-values-part-1\/#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 I)"}]},{"@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\/737"}],"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=737"}],"version-history":[{"count":25,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/posts\/737\/revisions"}],"predecessor-version":[{"id":13973,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/posts\/737\/revisions\/13973"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/media\/739"}],"wp:attachment":[{"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/media?parent=737"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/categories?post=737"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/tags?post=737"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.stratio.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=737"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}