The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

GavinBaumanis (10) [Avatar] Offline
Hi There,
On Page 45, in the section, Deifing immutable objects with Scala;
Is the following code snippet;

override def toString() = {
title + “($”+p+“)”

My question is; why?
I understand the code - but why would you alter the behaviour of an esiting / built-in / standard method? Would you you just not create a whole new one with an appropriate name?

From an ongoing maintenance perspective - wouldnt it add confusion, having standard methods, do non-standard things?

I appreciate also, it might just be an example "just" to show the syntax - as elluded to in the "comments" for the code... But to save people questioning, perhaps you could add something like; " You would probably never do this - but to show you the syntax..." - or similar.

perhaps - I have just been living under a rock for too long and it is common-place to override standard methods?

Gavin. (121) [Avatar] Offline
Re: Overide toString Method
Overriding 'toString' does make for friendlier output from the REPL. If you want to see what the standard (I think the better way to think of it would be as a "provided skeleton function", instead of a "standard function" in this case) toString does, you can define another similar class, but without the overridden 'toString', and then compare the two outputs:

class PlainBook(t:String, p:Price) {
    val title = t
    val price = p
val book2 = new PlainBook("Some book", 10)
book2: StrBook = StrBook@9556cd94

I dont think toString is that crucial a method that overriding it will cause any issues. Scala certainly doesnt rely on it to do its own memory tracking! It has its own internal mechanisms which I doubt you'll be able to override by merely redefining a function....