Search code examples
scalanumbersnotation

Scala, simple notation of Imaginary (number)


Imagine that I have the class Imaginary(x) and the class Real(y) in Scala. Is there a way to do ComplexNumber = 3 + 2i instead of doing ComplexNumber = Real(3) + Imaginary(2) ?

Thanks.


Solution

  • No, this is not possible. The lexical analysis phase of the compiler "owns" suffixes on numeric strings such as f (Float), d (Double) and l (Long) and there is no extensibility for this notation.

    You might want to think about using the new string interpolation mechanism to annotate constants. You'd have to accept parsing them and the "flag," if you will (your i), would have to be used in prefix position. That would give you something like this:

    val imaginary = i"1.2+3.4i"
    

    I'm not up-to-date with the capabilities of macros in the new compiler, but perhaps you could get the parsing done at compile time, which would preclude attempting to work with malformed values at run-time.

    This approach (whether compile-time or run-time parsed) would be flexible (insofar as you can be as accommodating as you like in the accepted formats) but it clearly does not match the notation that people use in mathematical texts.