7/21/2014

Implicit Parameters vs Default Parameter Values

There are, at least, two techniques in Scala to pass default value to a method

1) default parameter value
scala> def f(i: Int = 0) = i
f: (i: Int)Int

scala> f()
res0: Int = 0

scala> f(1)
res1: Int = 1
 
2) implicit parameter
scala> def g(implicit i: Int) = i
g: (implicit i: Int)Int

scala> implicit val default = 0
default: Int = 0

scala> g(1)
res5: Int = 1

scala> g
res7: Int = 0
In which case do you choose one or another ? With the power of implicit, default values are they a usefull feature ?

You should definitely prefer default parameter value.
  1. You should never create or use implicit parameters of general types like Int or String. See citation below.
  2. Default value is the simplest solution. In terms of language features complexity.
  3. Implicit parameters are for some kind of "context" for your method. If there is no context, just default value you can confuse other developers.
  4. Implicit value search will cost you some amount of compilation time.
  5. Implicit parameters should be specified manually only in rare cases.
---------
Real world examples of implicit params: Akka actors ActorRef method

def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit

Here we are automatically pass along the sender reference while sending a message to another Actor.
This code will, if invoked from within Actor 'A' automatically pass along the ActorRef of Actor 'A' as the sender of this message:

// From within an Actor
greeter ! Greet
        


No comments:

Post a Comment