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 ?
The other answers are interesting, and they raise the valid point that implicits result in slower compilation times and more complex code.
However, I think it is important to understand that, in one sense, implicits and defaults are complementary:
Naturally, it is possible for a library to provide implicits that will be used by its functions -- you use implicits all the time in the Scala library without having to define them, right?
However, when using implicits the caller can always specify a different "default" to be used.
In either case, one can explicitly pass the value when calling a function.
Another minor difference is that one can pick and choose which defaults to override through named parameters, but if you choose to pass one implicit explicitly, you have to pass all of them.
Finally, notice that you can use an implicit and a default at the same time.
If you declare a default value, then you'll always have that same default value. With implicits, the default value will depend on where the function is being used. For example, if you provide such a function:
whoever uses this function will listen on port 26000 if none specified. With implicits, the users of this function can define their own default for that value:
Now on a different package, you can use a different implicit:
This way, you can make your function more flexible, but It all depends on if it makes sense to be able to overwrite the value.
You can also combine both:
This will use an implicit value if available or default to 26000 if none.
You should definitely prefer default parameter value.
Int
orString
. See citation below.See also: Programming In Scala 21.5 Implicit parameters/A style rule for implicit parameters: