Good example of implicit parameter in Scala? [closed]

In a sense, yes, implicits represent global state. However, they are not mutable, which is the true problem with global variables -- you don't see people complaining about global constants, do you? In fact, coding standards usually dictate that you transform any constants in your code into constants or enums, which are usually global.

Note also that implicits are not in a flat namespace, which is also a common problem with globals. They are explicitly tied to types and, therefore, to the package hierarchy of those types.

So, take your globals, make them immutable and initialized at the declaration site, and put them on namespaces. Do they still look like globals? Do they still look problematic?

But let's not stop there. Implicits are tied to types, and they are just as much "global" as types are. Does the fact that types are global bother you?

As for use cases, they are many, but we can do a brief review based on their history. Originally, afaik, Scala did not have implicits. What Scala had were view types, a feature many other languages had. We can still see that today whenever you write something like T <% Ordered[T], which means the type T can be viewed as a type Ordered[T]. View types are a way of making automatic casts available on type parameters (generics).

Scala then generalized that feature with implicits. Automatic casts no longer exist, and, instead, you have implicit conversions -- which are just Function1 values and, therefore, can be passed as parameters. From then on, T <% Ordered[T] meant a value for an implicit conversion would be passed as parameter. Since the cast is automatic, the caller of the function is not required to explicitly pass the parameter -- so those parameters became implicit parameters.

Note that there are two concepts -- implicit conversions and implicit parameters -- that are very close, but do not completely overlap.

Anyway, view types became syntactic sugar for implicit conversions being passed implicitly. They would be rewritten like this:

def max[T <% Ordered[T]](a: T, b: T): T = if (a < b) b else a
def max[T](a: T, b: T)(implicit $ev1: Function1[T, Ordered[T]]): T = if ($ev1(a) < b) b else a

The implicit parameters are simply a generalization of that pattern, making it possible to pass any kind of implicit parameters, instead of just Function1. Actual use for them then followed, and syntactic sugar for those uses came latter.

One of them is Context Bounds, used to implement the type class pattern (pattern because it is not a built-in feature, just a way of using the language that provides similar functionality to Haskell's type class). A context bound is used to provide an adapter that implements functionality that is inherent in a class, but not declared by it. It offers the benefits of inheritance and interfaces without their drawbacks. For example:

def max[T](a: T, b: T)(implicit $ev1: Ordering[T]): T = if ($ev1.lt(a, b)) b else a
// latter followed by the syntactic sugar
def max[T: Ordering](a: T, b: T): T = if (implicitly[Ordering[T]].lt(a, b)) b else a

You have probably used that already -- there's one common use case that people usually don't notice. It is this:

new Array[Int](size)

That uses a context bound of a class manifests, to enable such array initialization. We can see that with this example:

def f[T](size: Int) = new Array[T](size) // won't compile!

You can write it like this:

def f[T: ClassManifest](size: Int) = new Array[T](size)

On the standard library, the context bounds most used are:

Manifest      // Provides reflection on a type
ClassManifest // Provides reflection on a type after erasure
Ordering      // Total ordering of elements
Numeric       // Basic arithmetic of elements
CanBuildFrom  // Collection creation

The latter three are mostly used with collections, with methods such as max, sum and map. One library that makes extensive use of context bounds is Scalaz.

Another common usage is to decrease boiler-plate on operations that must share a common parameter. For example, transactions:

def withTransaction(f: Transaction => Unit) = {
  val txn = new Transaction

  try { f(txn); txn.commit() }
  catch { case ex => txn.rollback(); throw ex }
}

withTransaction { txn =>
  op1(data)(txn)
  op2(data)(txn)
  op3(data)(txn)
}

Which is then simplified like this:

withTransaction { implicit txn =>
  op1(data)
  op2(data)
  op3(data)
}

This pattern is used with transactional memory, and I think (but I'm not sure) that the Scala I/O library uses it as well.

The third common usage I can think of is making proofs about the types that are being passed, which makes it possible to detect at compile time things that would, otherwise, result in run time exceptions. For example, see this definition on Option:

def flatten[B](implicit ev: A <:< Option[B]): Option[B]

That makes this possible:

scala> Option(Option(2)).flatten // compiles
res0: Option[Int] = Some(2)

scala> Option(2).flatten // does not compile!
<console>:8: error: Cannot prove that Int <:< Option[B].
              Option(2).flatten // does not compile!
                        ^

One library that makes extensive use of that feature is Shapeless.

I don't think the example of the Akka library fits in any of these four categories, but that's the whole point of generic features: people can use it in all sorts of way, instead of ways prescribed by the language designer.

If you like being prescribed to (like, say, Python does), then Scala is just not for you.


Sure. Akka's got a great example of it with respect to its Actors. When you're inside an Actor's receive method, you might want to send a message to another Actor. When you do this, Akka will bundle (by default) the current Actor as the sender of the message, like this:

trait ScalaActorRef { this: ActorRef =>
  ...

  def !(message: Any)(implicit sender: ActorRef = null): Unit

  ...
}

The sender is implicit. In the Actor there is a definition that looks like:

trait Actor {
  ...

  implicit val self = context.self

  ...
}

This creates the implicit value within the scope of your own code, and it allows you to do easy things like this:

someOtherActor ! SomeMessage

Now, you can do this as well, if you like:

someOtherActor.!(SomeMessage)(self)

or

someOtherActor.!(SomeMessage)(null)

or

someOtherActor.!(SomeMessage)(anotherActorAltogether)

But normally you don't. You just keep the natural usage that's made possible by the implicit value definition in the Actor trait. There are about a million other examples. The collection classes are a huge one. Try wandering around any non-trivial Scala library and you'll find a truckload.


One example would be the comparison operations on Traversable[A]. E.g. max or sort:

def max[B >: A](implicit cmp: Ordering[B]) : A

These can only be sensibly defined when there is an operation < on A. So, without implicits we’d have to supply the context Ordering[B] every time we’d like to use this function. (Or give up type static checking inside max and risk a runtime cast error.)

If however, an implicit comparison type class is in scope, e.g. some Ordering[Int], we can just use it right away or simply change the comparison method by supplying some other value for the implicit parameter.

Of course, implicits may be shadowed and thus there may be situations in which the actual implicit which is in scope is not clear enough. For simple uses of max or sort it might indeed be sufficient to have a fixed ordering trait on Int and use some syntax to check whether this trait is available. But this would mean that there could be no add-on traits and every piece of code would have to use the traits which were originally defined.

Addition:
Response to the global variable comparison.

I think you’re correct that in a code snipped like

implicit val num = 2
implicit val item = "Orange"
def shopping(implicit num: Int, item: String) = {
  "I’m buying "+num+" "+item+(if(num==1) "." else "s.")
}

scala> shopping
res: java.lang.String = I’m buying 2 Oranges.

it may smell of rotten and evil global variables. The crucial point, however, is that there may be only one implicit variable per type in scope. Your example with two Ints is not going to work.

Also, this means that practically, implicit variables are employed only when there is a not necessarily unique yet distinct primary instance for a type. The self reference of an actor is a good example for such a thing. The type class example is another example. There may be dozens of algebraic comparisons for any type but there is one which is special. (On another level, the actual line number in the code itself might also make for a good implicit variable as long as it uses a very distinctive type.)

You normally don’t use implicits for everyday types. And with specialised types (like Ordering[Int]) there is not too much risk in shadowing them.


Based on my experience there is no real good example for use of implicits parameters or implicits conversion.

The small benefit of using implicits (not needing to explicitly write a parameter or a type) is redundant in compare to the problems they create.

I am a developer for 15 years, and have been working with scala for the last 1.5 years.

I have seen many times bugs that were caused by the developer not aware of the fact that implicits are used, and that a specific function actually return a different type that the one specified. Due to implicit conversion.

I also heard statements saying that if you don't like implicits, don't use them. This is not practical in the real world since many times external libraries are used, and a lot of them are using implicits, so your code using implicits, and you might not be aware of that. You can write a code that has either:

import org.some.common.library.{TypeA, TypeB}

or:

import org.some.common.library._

Both codes will compile and run. But they will not always produce the same results since the second version imports implicits conversion that will make the code behave differently.

The 'bug' that is caused by this can occur a very long time after the code was written, in case some values that are affected by this conversion were not used originally.

Once you encounter the bug, its not an easy task finding the cause. You have to do some deep investigation.

Even though you feel like an expert in scala once you have found the bug, and fixed it by changing an import statement, you actually wasted a lot of precious time.

Additional reasons why I generally against implicits are:

  • They make the code hard to understand (there is less code, but you don't know what he is doing)
  • Compilation time. scala code compiles much slower when implicits are used.
  • In practice, it changes the language from statically typed, to dynamically typed. Its true that once following very strict coding guidelines you can avoid such situations, but in real world, its not always the case. Even using the IDE 'remove unused imports', can cause your code to still compile and run, but not the same as before you removed 'unused' imports.

There is no option to compile scala without implicits (if there is please correct me), and if there was an option, none of the common community scala libraries would have compile.

For all the above reasons, I think that implicits are one of the worst practices that scala language is using.

Scala has many great features, and many not so great.

When choosing a language for a new project, implicits are one of the reasons against scala, not in favour of it. In my opinion.