How to call super method when overriding a method through a trait

后端 未结 3 1951
南笙
南笙 2020-12-29 06:19

It would appear that it is possible to change the implementation of a method on a class with a trait such as follows:

trait Abstract { self: Result =>
            


        
3条回答
  •  余生分开走
    2020-12-29 06:53

    I don't know if you are in a position to make the following changes, but the effect you want can be achieved by introducing an extra trait (I'll call it Repr), and using abstract override in the Abstract trait:

    trait Repr {
        def userRepr: String
    }
    
    abstract class Result extends Repr {
        def userRepr: String = "wtv"
    }
    
    case class ValDefResult(name: String) extends Result {
        override def userRepr = name
    }
    
    trait Abstract extends Repr { self: Result =>
        abstract override def userRepr = "abstract-" + super.userRepr // 'super.' works now
    }
    

    Your example usage now gives:

    scala> val a = new ValDefResult("asd") with Abstract
    a: ValDefResult with Abstract = ValDefResult(asd)
    
    scala> a.userRepr
    res3: String = abstract-asd
    

提交回复
热议问题