How to mix-in a trait to instance?

前端 未结 5 1392
日久生厌
日久生厌 2020-12-04 12:04

Given a trait MyTrait:

trait MyTrait {
  def doSomething = println(\"boo\")
}

it can be mixed into a class with extends<

5条回答
  •  粉色の甜心
    2020-12-04 12:50

    What about an implicit class? It seems easier to me compared to the way in the other answers with a final inner class and a "mixin"-function.

    trait MyTrait {
    
        def traitFunction = println("trait function executed")
    
    }
    
    class MyClass {
    
        /**
         * This inner class must be in scope wherever an instance of MyClass
         * should be used as an instance of MyTrait. Depending on where you place
         * and use the implicit class you must import it into scope with
         * "import mypackacke.MyImplictClassLocation" or
         * "import mypackage.MyImplicitClassLocation._" or no import at all if
         * the implicit class is already in scope.
         * 
         * Depending on the visibility and location of use this implicit class an
         * be placed inside the trait to mixin, inside the instances class,
         * inside the instances class' companion object or somewhere where you
         * use or call the class' instance with as the trait. Probably the
         * implicit class can even reside inside a package object. It also can be
         * declared private to reduce visibility. It all depends on the structure
         * of your API.
         */
        implicit class MyImplicitClass(instance: MyClass) extends MyTrait
    
        /**
         * Usage
         */
        new MyClass().traitFunction
    
    }
    

提交回复
热议问题