Search code examples
scalastringbuilder

What's the correct way to convert from StringBuilder to String?


From what I've seen online, people seem to suggest that the toString() method is to be used, however the documentation states:

Creates a String representation of this object. The default representation is platform dependent. On the java platform it is the concatenation of the class name, "@", and the object's hashcode in hexadecimal.

So it seems like using this method might cause some problems down the line?

There is also mkString and result(). The latter of which seems to make the most sense. But I'm not sure what the differences between these 3 methods are and if that's how result() is supposed to be used.


Solution

  • The toString implementation currently just redirects to the result method anyway, so those two methods will behave in the same way. However, they express slightly different intent:

    • toString requests a textual representation of StringBuilders current state that is "concise but informative (and) that is easy for a person to read". So, theoretically, the (vague) specification of this method does not forbid abbreviating the result, or enhancing conciseness and readability in any other way.
    • result requests the actual constructed string. No different readings seem possible here.

    Therefore, if you want to obtain the resulting string, use result to express your intent as clearly as possible.

    In this way, the reader of your code won't have to wonder whether StringBuilder.toString might shorten something for the sake of "conciseness" when the string gets over 9000 kB long, or something like that.

    The mkString is for something else entirely, it's mostly used for interspersing separators, as in "hello".mkString(",") == "h,e,l,l,o".

    Some further links:

    Just use result().