Scala for the Impatient: Chapter 5 exercises solutions

I’ve started going through the book: Scala for the Impatient by Cay Horstmann. I’m posting the solution to chapter 5 exercises below.

Advertisements

3 thoughts on “Scala for the Impatient: Chapter 5 exercises solutions

  1. Hello, i want to improve 8 solution. You wrote:

    class Car(val manufacturer: String, val modelName: String, val modelYear: Int, var licensePlate: String) {
    def this(manufacturer: String, modelName: String, licensePlate: String) = {
    this(manufacturer, modelName, -1, licensePlate)
    }

    def this(manufacturer: String, modelName: String, modelYear: Int) = {
    this(manufacturer, modelName, modelYear, “”)
    }

    def this(manufacturer: String, modelName: String) = {
    this(manufacturer, modelName, -1, “”)
    }

    override def toString = {
    “[” + manufacturer + “, ” + modelName + “, ” + modelYear + “, ‘” + licensePlate + “‘]”
    }
    }

    What is bad? First, verbosity. You can use default values (see advice from chapter 5.7). Look ver. 2.

    Ok, we got rid of the two constructors. But that’s not all. There is a pitfall. If you try create new Car(“Ferrary”, “GT”, licensePlate = “GR135”), you will get “ambiguous reference to overloaded definition”. Because both constructors match argument types. So, i think best solution (ver. 3)

    It’s short and does not cause unexpected behavior

  2. Your comment is awaiting moderation.
    Hello, i want to improve 8 solution. You wrote (original)

    What is bad? First, verbosity. You can use default values (see advice from chapter 5.7). Look ver. 2.

    Ok, we got rid of the two constructors. But that’s not all. There is a pitfall. If you try create new Car(“Ferrary”, “GT”, licensePlate = “GR135″), you will get “ambiguous reference to overloaded definition”. Because both constructors match argument types. So, i think best solution (ver. 3)

    It’s short and does not cause unexpected behavior

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s