Why is “abstract override” required not “override” alone in subtrait?

前端 未结 3 1135
再見小時候
再見小時候 2020-12-08 04:21

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 m

3条回答
  •  青春惊慌失措
    2020-12-08 05:12

    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) }
    }
    :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
    

提交回复
热议问题