Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Default parameter value derived from previous parameters

Tags:

scala

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?

like image 693
Tactical Catgirl Avatar asked Dec 25 '13 03:12

Tactical Catgirl


People also ask

Can you assign the default values to a function parameters?

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.

What is the default value for string in Scala?

def aMethod(param: String = "asdf") = { ... } If the method is called as follows, then param is given the default value "asdf": aMethod() ...

Where the default value of the parameter have to be specified?

We can provide a default value to a particular argument in the middle of an argument list.


1 Answers

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.

like image 82
senia Avatar answered Sep 27 '22 19:09

senia