LoginSignup
3
2

More than 5 years have passed since last update.

Scalaのimplicitのユースケース

Last updated at Posted at 2016-12-15

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)
    }
  }

3
2
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
2