Search code examples
scalaoverridingtostringdefault-parameters

overriding toString in scala and creating a second toString method with default parameters


I have a complex-number-related class for which I wrote the following code:

override def toString: String = toString()

def toString(precision: Int = 2, showImag:Boolean = true): String = ???

The implementation of the second method is not important. The problem with this is that toString() will call toString and will recurse endlessly. I could replace toString() with toString(2), but I think that is ugly, as the 2 is already implied. Is there a way to use the second function without specifying parameters or renaming the function?


EDIT:

As the answer and comments showed it isn't possible (read their explanation why). I realized that a way to get around this is by creating an private method with a different name that is called by the other two public methods and contains the actual implementation, like so:

override def toString: String = toStringImpl(2, true)

def toString(precision: Int = 2, showImag:Boolean = true): String = toStringImpl(precision, showImag)

private def toStringImpl(precision: Int, showImag:Boolean): String = ???

You could say that this is more lines of code and you could say that it indeed doesn't give a parameter that was already default. Both approaches work and I think it would be subjective to further discuss which approach is better as both have their advantages and disadvantages.


Solution

  • Is there a way to use the second function without specifying parameters or renaming the function?

    Whatever you do, toString() will call the toString() inherited from Any, because it's the most specific matching method.