10

I have a following function:

def getIntValue(x: Int)(implicit y: Int ) : Int = {x + y}

I see above declaration everywhere. I understand what above function is doing. It is a currying function which takes two arguments. If you omit the second argument, it will invoke implicit definition which returns int instead. So I think it is something very similar to defining a default value for the argument.

implicit val temp = 3

scala> getIntValue(3)
res8: Int = 6

I was wondering what are the benefits of above declaration?

3 Answers 3

11

In your specific example there are no practical benefits. In fact using implicits for this task will only obfuscate your code.

The standard use case of implicits is the Type Class Pattern. I'd say that it is the only use case that is practically useful. In all other cases it's better to have things explicit.

Here is an example of a typeclass:

// A typeclass
trait Show[a] {
  def show(a: a): String
}

// Some data type
case class Artist(name: String)

// An instance of the `Show` typeclass for that data type
implicit val artistShowInstance =
  new Show[Artist] {
    def show(a: Artist) = a.name
  }

// A function that works for any type `a`, which has an instance of a class `Show`
def showAListOfShowables[a](list: List[a])(implicit showInstance: Show[a]): String =
  list.view.map(showInstance.show).mkString(", ")

// The following code outputs `Beatles, Michael Jackson, Rolling Stones`
val list = List(Artist("Beatles"), Artist("Michael Jackson"), Artist("Rolling Stones"))
println(showAListOfShowables(list))

This pattern originates from a functional programming language named Haskell and turned out to be more practical than the standard OO practices for writing a modular and decoupled software. The main benefit of it is it allows you to extend the already existing types with new functionality without changing them.

There's plenty of details unmentioned, like syntactic sugar, def instances and etc. It is a huge subject and fortunately it has a great coverage throughout the web. Just google for "scala type class".

2
10

Here's my "pragmatic" answer: you typically use currying as more of a "convention" than anything else meaningful. It comes in really handy when your last parameter happens to be a "call by name" parameter (for example: : => Boolean):

def transaction(conn: Connection)(codeToExecuteInTransaction : => Boolean) = {

   conn.startTransaction  // start transaction

   val booleanResult = codeToExecuteInTransaction //invoke the code block they passed in

  //deal with errors and rollback if necessary, or commit
  //return connection to connection pool
}

What this is saying is "I have a function called transaction, its first parameter is a Connection and its second parameter will be a code-block".

This allows us to use this method like so (using the "I can use curly brace instead of parenthesis rule"):

transaction(myConn) {

   //code to execute in a transaction
  //the code block's last executable statement must be a Boolean as per the second
  //parameter of the transaction method

}

If you didn't curry that transaction method, it would look pretty unnatural doing this:

transaction(myConn, {

   //code block

})

How about implicit? Yes it can seem like a very ambiguous construct, but you get used to it after a while, and the nice thing about implicit functions is they have scoping rules. So this means for production, you might define an implicit function for getting that database connection from the PROD database, but in your integration test you'll define an implicit function that will superscede the PROD version, and it will be used to get a connection from a DEV database instead for use in your test.

As an example, how about we add an implicit parameter to the transaction method?

def transaction(implicit conn: Connection)(codeToExecuteInTransaction : => Boolean) = {

}

Now, assuming I have an implicit function somewhere in my code base that returns a Connection, like so:

def implicit getConnectionFromPool() : Connection = { ...}

I can execute the transaction method like so:

transaction {
   //code to execute in transaction
}

and Scala will translate that to:

transaction(getConnectionFromPool) {
  //code to execute in transaction
}

In summary, Implicits are a pretty nice way to not have to make the developer provide a value for a required parameter when that parameter is 99% of the time going to be the same everywhere you use the function. In that 1% of the time you need a different Connection, you can provide your own connection by passing in a value instead of letting Scala figure out which implicit function provides the value.

5

There are many benefits, outside of your example. I'll give just one; at the same time, this is also a trick that you can use on certain occasions.

Imagine you create a trait that is a generic container for other values, like a list, a set, a tree or something like that.

trait MyContainer[A] {
  def containedValue:A
}

Now, at some point, you find it useful to iterate over all elements of the contained value. Of course, this only makes sense if the contained value is of an iterable type.

But because you want your class to be useful for all types, you don't want to restrict A to be of a Seq type, or Traversable, or anything like that. Basically, you want a method that says: "I can only be called if A is of a Seq type." And if someone calls it on, say, MyContainer[Int], that should result in a compile error.

That's possible. What you need is some evidence that A is of a sequence type. And you can do that with Scala and implicit arguments:

trait MyContainer[A] {
  def containedValue:A
  def aggregate[B](f:B=>B)(implicit ev:A=>Seq[B]):B =
    ev(containedValue) reduce f
}

So, if you call this method on a MyContainer[Seq[Int]], the compiler will look for an implicit Seq[Int]=>Seq[B]. That's really simple to resolve for the compiler. Because there is a global implicit function that's called identity, and it is always in scope. Its type signature is something like: A=>A

It simply returns whatever argument is passed to it.

I don't know how this pattern is called. (Can anyone help out?) But I think it's a neat trick that comes in handy sometimes. You can see a good example of that in the Scala library if you look at the method signature of Seq.sum. In the case of sum, another implicit parameter type is used; in that case, the implicit parameter is evidence that the contained type is numeric, and therefore, a sum can be built out of all contained values.

That's not the only use of implicits, and certainly not the most prominent, but I'd say it's an honorable mention. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.