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 ?
Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
Default (Optional) Parameters A default parameter is one that need not necessarily be provided by the caller; if it is missing, then a preestablished default value will be used instead.
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
You should definitely prefer default parameter value.
Int
or String
. See citation below.See also: Programming In Scala 21.5 Implicit parameters/A style rule for implicit parameters:
As a style rule, it is best to use a custom named type in the types of implicit parameters.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With