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

后端 未结 3 1946
南笙
南笙 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:50

    Here is the answer I was looking for. Thank you Shadowlands for pointing me in the right direction with Scala's abstract override feature.

    trait Abstract extends Result {
        abstract override def userRepr = "abstract " + super.userRepr
    }
    
    abstract class Result {
        def userRepr: String = "wtv"
    }
    
    case class ValDefResult(name: String) extends Result {
        override def userRepr = name
    }
    
    val a = new ValDefResult("asd") with Abstract
    a.userRepr
    

    Live code is available here: http://www.scalakata.com/52536cc2e4b0b1a1c4daa4a4

    Sorry for the confusing example code, I am writing a library that deals with the Scala AST and was not inspired enough to change the names.

提交回复
热议问题