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

前端 未结 3 1131
再見小時候
再見小時候 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:11

    A part of late binding in scala traits posts; provides a very clear explanation; provided verbatim bellow (read the full post for more info):

    The abstract base class provided an implementation of the requestApproval method. This is good since the leftmost trait calls this method. What happens if the base class’s method is abstract?

    abstract class ApprovalRequest {
      def requestApproval()
    }
    

    If we change this, we get a rather odd message from the compiler: error: method requestApproval in class ApprovalRequest is accessed from super. It may not be abstract unless it is overridden by a member declared abstract and override The combination of abstract and override tells the compiler that the final implementation of the method will be provided by the class mixing-in the trait. If we add the abstract keyword to the methods, we can no longer use our anonymous implementation of ApprovalRequest. That object can’t be created since the abstract override methods will be looking for an implementation of requestApproval and there isn’t one. Instead we have to create a new class that extends ApprovalRequest and implements requestApproval. We then mix the traits into an instance of that class.

    class ApprovalDelegate extends ApprovalRequest {
      override def requestApproval() {
        println("and now we play the waiting game")
      }
    }
    
    val adCampaign = new ApprovalDelegate with MarketingApprovalRequest
       with FinanceApprovalRequest with ExecutiveApprovalRequest
    

    Which will now give the output:

    requesting approaval from executives
    requesting approval from Finance
    requesting approval from Marketing
    and now we play the waiting game
    

提交回复
热议问题