LoginSignup
3
0

More than 5 years have passed since last update.

Scala:自分型アノテーションでDI

Posted at

実装

インターフェース定義

trait Impl {
  def hello:String 
}

実装トレイト

trait M extends Impl { //インターフェースを継承する
  override def hello="i am mama"
}

trait P extends Impl { //インターフェースを継承する
  override def hello="i am papa"
}

共通処理

trait C {
  def shout(t:String):String={
    "%s Gyaaa!!!".format(t)
  }
}

利用クラス

class F extends C {
  self:Impl => //自分型アノテーションにインターフェースを設定する
    def greeting:Unit={
      println(shout(hello))
    }
}

利用方法

val mama = new F with M  //helloの実装をココで注入
mama.greeting

val papa= new F with P  //helloの実装をココで注入
papa.greeting

実行結果

i am mama Gyaaa!!!
i am papa Gyaaa!!!
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0