In Scala how can I advise my own methods?

后端 未结 1 1141
我寻月下人不归
我寻月下人不归 2021-01-23 03:48

I want to do this:

trait Renderable {
    def render: String
}

trait Parens extends Renderable {
    abstract override def render = \"(\" + super.render + \")\"         


        
相关标签:
1条回答
  • 2021-01-23 04:38

    How about separating the presentation logic (render) and the actual contents (value)?

    trait Renderable {
      def value : String
      def render = value // default presentation logic, simple rendering.
    }
    
    trait Parens extends Renderable {
      override def render :String = "(" + value + ")" // parens rendering.
    }
    
    object Foo extends Parens {
      def value = "Hello"
    }
    
    println(Foo.render) // prints '(Hello)'
    

    Edit

    Found a way you can do pretty much what you wanted, check it out:

    trait Renderable {
      def render: String
    }
    
    trait Parens extends Renderable {
      abstract override def render = "(" + super.render + ")"
    }
    
    class Foo extends Renderable {
      def render = "Hello"
    }
    
    val foo = new Foo with Parens
    println(foo.render)
    

    You can't use an object since you need to implement the trait at creation time, but if you can control the instance creation then this might work :).

    I'm pretty sure it's not possible to do it otherwise (someone please correct me if I'm wrong)

    0 讨论(0)
提交回复
热议问题