Assume that we have a class constructor that takes parameters that have default value.
class A(val p1 : Int = 3, val p2 : Int = 4)
Let's say I don't have control over this class and can't modify it in anyway. What I want to do is to call A's constructor with p1 = 5, p2 = (if condition1 == true then 5 else default value). One way to do this is
if(condition1)
x = new A(5,5)
else
x = new A(5)
As you can see, this can easily get big if there are many parameters and each must be supplied conditionally. What I want is something like
x = new A(p1 = 5, p2 = <if condition1 = true then 5 else default>)
How can I do that? Note that the fields in class A are vals, so I cant change them after instantiating A.
It seems to me you have three possibilities:
Create variables to hold each of the values you want to specify, do all the code to fill in the values, and instantiate A
once at the end. This requires knowing the default values, as Ionut mentioned. I don't think creating a throwaway object to read the defaults is all that hackish -- certainly not as much as embedding the defaults themseves -- but whatever.
Use the reflection API to create A
. I'm not exactly sure how to do that but almost certainly you can pass in a list of parameters, with any unspecified parameters defaulted. This requires Scala 2.10; before that, only the Java reflection API was available and you'd have to hack through the internal implementation of optional parameters, which is hackish.
Use macros. Also 2.10+. I think that quasiquotes should make it possible to do this without too much difficulty, although I'm not too familiar with them so I can't say for sure.
Fetch the default values,
val defaultA = new A()
Then
val x = new A(p1 = 5, p2 = if (cond) 5 else defaultA.p2)
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