Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd Scala operators to final Java class
    primarykey
    data
    text
    <p>I am using the jMonkeyEngine (Java Game Engine) in Scala, which works out pretty well so far, but now I am asking myself whether there is an elegant way of overloading operators for the <code>Vector3f</code> (and similar) classes. My first idea was to inherit from <code>Vector3f</code> and overload the operators, but <code>Vector3f</code> is final, so that is not an option. Next I thought maybe I could have a singleton/scala object with static methods that operate on <code>Vector3f</code>, like below, but that does not work either:</p> <pre><code>object VectorMath { def *(factor: Float, vector: Vector3f) = vector.mult(factor) } //and then somewhere import VectorMath._ var v = new Vector3f(1,2,3); var u = 1.2f * v; //this does not work, because Float does not have * overloaded for Vector3f var u = VectorMath.*(1.2f, v); //this does work, but defeats the purpose </code></pre> <p>So all I can think of now is to wrap the Vector3f in a new Scala class and delegate the operator calls to the appropriate Java methods. This has, however, three downsides:</p> <ol> <li>I will have to do to a lot of back and forth conversions (a <code>toVector3f</code> and a <code>fromVector3f</code> method or something like that).</li> <li>This problem becomes even worse when I have arrays of Vector3f/ScalaVectors. Since the classes are not related (except by composition), I would have to manually cast every element of the array every time I call a method in jME. </li> <li>Even then I know of no way to overload an operator for my new ScalaVector class in such a way that I could have the factor in front, i.e. <code>1.2f * v</code>.</li> </ol> <p>My question: Can someone think of a way to make this more natural/elegant? How do you tackle similar problems? Or is there maybe a Scala syntax that I don know of to do these kinds of things? In C++ I would make a global operator that takes float and Vector3f as arguments and possibly friend it. Whats the Scala way to do this, or is that simply not possible?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload