Is there any way to do something like this
class Foo (val bar:Any, val baz:Any = magic(bar))
without overloading constructor or making baz mutable?
Default parameter in JavascriptThe 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.
def aMethod(param: String = "asdf") = { ... } If the method is called as follows, then param is given the default value "asdf": aMethod() ...
We can provide a default value to a particular argument in the middle of an argument list.
You should use different parameter groups:
def test(i: Int)(j: Int = i + 1) = i + j
test(1)()
// Int = 3
class Foo (val bar: Int)(val baz: Int = bar + 1)
new Foo(1)().baz
// Int = 2
For constructors you could also use None for default value of constructor parameter and then define val in class body:
class Foo (val bar: Int, _baz: Option[Int] = None) {
  val baz = _baz.getOrElse(bar + 1)
}
new Foo(1).baz
// Int = 2
Note that for case class you can't use different parameter groups (if you want to get all parameters in unapply) nor class body. The only way is to define an addition apply method in companion object.
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