I was writing code for something like an array with variable dimensions. What I do is to maintain a linear underlying collections and wrap it up with index access methods. Since the dimension of the data structure is not known, I write something like
def apply(i: Int*): Double = ...
And it works perfectly. However, I cannot do the same thing to update method and operators like +=, so I end up writing methods like
def set(v: Double, i: Int*) ...
def add(v: Double, i: Int*) ...
which is fine but not what I really want. I guess the problem about update may be fixed in two ways:
- Change the order of arguments in update function, which makes it look weird.
- Allow variable-length arguments not as the last one. I find this questions asked in a general setting and it can be solved by using currying functions, which does not apply here.
The problem about += seems more complicated and it even exists when the index is of fixed length. Maybe we can add an object that has += operator and use this(…) to get the object (so that this(…) += v will invoke some method as we expect), but that will conflict with the apply method.
If anyone has solution to any of the above questions or has a reason why we shouldn’t be able to write code like this, please share your ideas! Thanks~
The simplest solution I see right now is to have many different overloads of
updatefor every dimension that you want to support. Say that you can determine that the maximum dimension that you’ll ever use is 10, this means that you’ll need 10 overloads. This might not seem very practical, but i can easily be abstracted away so it is very much practical actually:Usage:
And some test in the REPL: