Scalaのimplicitキーワードのユースケースを整理する。
pimp my library
ユースケース: 既存のクラスに、メソッドを追加する。
implicit class RichString(val src:String) {
def sing:String = src + " duck";
}
"hello".sing // "hello duck"
implicit parameter(1)
ユースケース: ダイナミックスコープみたいに、引数で明示せずにコンテキストを変更する。
// 関数定義:
def do_some_db_manipulation(...)(implicit con:Connection) {
con.select(...)
}
// 呼び出し:
implicit val cona = connect(...)
do_some_db_manipulation() // use cona as con:Connection
implicit parameter(2)
ユースケース: Haskellの型クラスのようなものを実現する。
// 型クラスの定義
trait Duck[A] {
def sing(a:A):Unit
}
implicit object DuckInt extends Duck[Int] {
def sing(a:Int) = println("Int:%d".format(a))
}
implicit object DuckString extends Duck[String] {
def sing(a:String) = println("String:%s".format(a))
}
// 呼び出す側
def sings[A](xs: List[A])(implicit m:Duck[A]) = {
for ( x <- xs ) {
m.sing(x)
}
}
// test
sings(List(1,2,3))
sings(List("a","b","c"))
// implicitlyを使ったシュガーシンタックス。singsと同義
def sings2[A:Duck](xs: List[A]) = {
for ( x <- xs ) {
implicitly[Duck[A]].sing(x)
}
}