LoginSignup
1
0

More than 5 years have passed since last update.

Scalaのimplicit(暗黙)に関する理解のためのメモ

Posted at

概要

Scalaではimplicit(暗黙)という機能があり、おそらくScala未経験の人はこの機能が使われているソースを見て、かなり戸惑うと思います。(私も戸惑いました)
implicitの動作については@miyatin0212さんのScala implicit修飾子 まとめにて、詳しくまとめられていますが、自分なりに理解した内容とサンプルコードをメモとして残しておきます。

理解&サンプルコード

1_暗黙の引数

implicitの変数を引数に設定することで、メソッド呼び出し時に引数の設定を省略することが出来ます。サンプルコードは以下です、実行結果は「11」になります。

  // 1_暗黙の引数メソッド
  def returnInt(implicit param:Int):Int = {
     param + 5
  }
  implicit val param = 6
  println(returnInt)

2_暗黙のメソッド

引数に暗黙的にメソッドを呼び出したいクラスを設定することで、通常コンパイルエラー等発生する場合でも自動的にメソッドを補完する機能です。サンプルコードは以下です、実行結果は「7」になります。

  // テスト用の空クラス
  case class TestEmptyClass(){}

  // 2_暗黙のメソッド
  implicit def returnInt(param:TestEmptyClass):Int = {
    3
  }

  // 空クラスの作成
  val test = TestEmptyClass()
  println(4 + test)

3_暗黙のクラス

引数にメソッド等を拡張したいクラスを設定することで、自動的にクラスを補完してくれる機能です。サンプルコードは以下です、実行結果は「testclass」になります。

  // テスト用の空クラス
  case class TestEmptyClass(){}

  // 3_暗黙のクラス
  implicit class ImpClass(param:TestEmptyClass){
    def plintTest= {
      println("testclass")
    }
  }

  // 空クラスの作成
  val test = TestEmptyClass()
  test.plintTest
1
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
1
0