Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a parameter's default value reference another parameter?

How can a parameter's default value reference another parameter? If it cannot, how to work around that?

case class A(val x:Int, val y:Int = x*2)

Error (reasonably enough):

scala> case class B(val x:Int, val y:Int = x*2)
<console>:7: error: not found: value x
   case class B(val x:Int, val y:Int = x*2)
                                       ^
like image 267
Dominykas Mostauskis Avatar asked Jun 15 '13 16:06

Dominykas Mostauskis


People also ask

Can parameters have default values?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

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.

Is C++ pass by reference by default?

In C++, primitive data types (such as int , char , etc.) are pass by value by default. However, they can be passed by reference using the & operator. The non-primitive data types are pass by reference by default, as the reference to the object is passed to the function.


1 Answers

This requires that you use multiple parameter lists:

case class A(x: Int)(y: Int = x*2)

Default values can only refer to parameters in preceding lists.

Be careful however with case classes, because their equality only takes into the account the first parameter list, therefore:

A(1)() == A(1)(3)  // --> true!!
like image 123
0__ Avatar answered Oct 19 '22 07:10

0__