Good example of implicit parameter in Scala?

greenoldman picture greenoldman · Mar 2, 2012 · Viewed 22.2k times · Source

So far implicit parameters in Scala do not look good for me -- it is too close to global variables, however since Scala seems like rather strict language I start doubting in my own opinion :-).

Question: could you show a real-life (or close) good example when implicit parameters really work. IOW: something more serious than showPrompt, that would justify such language design.

Or contrary -- could you show reliable language design (can be imaginary) that would make implicit not neccessary. I think that even no mechanism is better than implicits because code is clearer and there is no guessing.

Please note, I am asking about parameters, not implicit functions (conversions)!

Updates

Global variables

Thank you for all great answers. Maybe I clarify my "global variables" objection. Consider such function:

max(x : Int,y : Int) : Int

you call it

max(5,6);

you could (!) do it like this:

max(x:5,y:6);

but in my eyes implicits works like this:

x = 5;
y = 6;
max()

it is not very different from such construct (PHP-like)

max() : Int
{
  global x : Int;
  global y : Int;
  ...
}

Derek's answer

This is great example, however if you can think of as flexible usage of sending message not using implicit please post an counter-example. I am really curious about purity in language design ;-).

Answer

Daniel C. Sobral picture Daniel C. Sobral · Mar 2, 2012

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.