1

I'm trying to understand the syntax for inheriting one class from another and it seems I must announce the constructor parameters of the parent when I create the child?

Why does this code not compile?

  class Animal(name:String)
  class Dog extends Animal //Here is where compiler error occurs

But this does

  class Animal(name:String)
  class Dog(name:String ) extends Animal(name)

Is their a reason I must explicitly say extends Animal(name) and not just extends Animal and the constructor be implied?

2 Answers 2

4

The Scala Language Specification doesn't (as far as I can see) discuss the reasons, but providing an implied constructor would be a special case, and would arguably be less clear.

Note that you can do things like:

class Animal(name:String)
class Dog extends Animal("Dog")

and

class Animal(name:String)
class Dog(n1: String, n2: String) extends Animal(n1 + n2)

So the current behaviour accommodates a variety of patterns in a uniform and explicit way.

Sign up to request clarification or add additional context in comments.

Comments

1

Let's say you have two constructors for Animal:

class Animal(name:String) {
  def this() = this("unnamed")
}

Which of them would you expect class Dog(name:String) extends Animal to use?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.