Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

scala - Why is "abstract override" required not "override" alone in subtrait?

I read the section of Programming in Scala where abstract override is introduced, but I'm still confused by what exactly is signified by the joining of these modifiers. The snippet of code in which these modifiers is used is pasted below:

trait Doubling extends IntQueue {
    abstract override def put(x: Int) { super.put(2 * x) }
}

In particular, I am confused by the purpose of abstract in this case, and why we cannot achieve the expected results simply with the override keyword. If we did not include a call to super, would we need the keyword abstract? Why or why not? I'm looking for a detailed explanation of this keyword combo as it pertains to stackable traits.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason is that the base class method is abstract

abstract class IntQueue {
  def get(): Int
  def put(x: Int)
}

If you were to not put abstract on the trait you end up with the explanation you were seeking:

trait Doubling extends IntQueue {
     override def put(x: Int) { super.put(2 * x) }
}
<console>:9: error: method put in class IntQueue is accessed from
 super. It may not be abstract unless it is overridden by a member 
 declared `abstract' and `override'
            override def put(x: Int) { super.put(2 * x) }

So - you would need to mark the method as abstract.

Here is the "other side" of the equation: if the methods do have implementations then it is not necessary to mark the trait's method as abstract:

 abstract class IntQueue {
    import collection.mutable._
        val q  =  Queue[Int]()
      def get(): Int = { q.dequeue() }
      def put(x: Int) = { q.enqueue(x) }
   }

It is now unnecessary to include abstract

 trait Doubling extends IntQueue {
        /* Look Ma! no abstract here ! */   override def put(x: Int) { super.put(2 * x) }
      }
defined trait Doubling

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...