Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala optionally supply named default parameter

Tags:

scala

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.

like image 331
DSR Avatar asked Oct 17 '13 17:10

DSR


2 Answers

It seems to me you have three possibilities:

  1. 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.

  2. 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.

  3. 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.

like image 56
Urban Vagabond Avatar answered Sep 21 '22 17:09

Urban Vagabond


Fetch the default values,

val defaultA = new A()

Then

val x = new A(p1 = 5, p2 = if (cond) 5 else defaultA.p2)
like image 31
elm Avatar answered Sep 20 '22 17:09

elm