There are, at least, two techniques in Scala to pass default value to a method
1) default parameter value
You should definitely prefer default parameter value.
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
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 parameterscala> 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.
- You should never create or use implicit parameters of general types like
Int
orString
. See citation below. - Default value is the simplest solution. In terms of language features complexity.
- Implicit parameters are for some kind of "context" for your method. If there is no context, just default value you can confuse other developers.
- Implicit value search will cost you some amount of compilation time.
- 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