Locked History Actions

Diff for "scala/implicit"

Differences between revisions 1 and 2
Deletions are marked like this. Additions are marked like this.
Line 9: Line 9:
  
  class ThisIsImplicitSample(value: Int) {
    override def toString = { "ThisIsImplicitSample:" + value }

  class Sample(value: Int) {
    override def toString = { "Sample:" + value }
Line 13: Line 13:
  
Line 15: Line 15:
  implicit val sample = new ThisIsImplicitSample(1)
  
  implicit val toBeImplicitArg = new Sample(1);
Line 18: Line 18:
  def methodWithImplicitArg(implicit s: ThisIsImplicitSample) {   def methodWithImplicitArg(implicit s: Sample) {
Line 21: Line 21:
  
Line 24: Line 24:
    methodWithImplicitArg(new ThisIsImplicitSample(2)) // 明示的に供給     methodWithImplicitArg(new Sample(2)) // 明示的に供給
    // methodWithImplicitArg() ... この場合、()をつけてはだめ。引数が不足と言われてしまう。
Line 30: Line 31:
methodWithImplicitArg called:ThisIsImplicitSample:1
methodWithImplicitArg called:ThisIsImplicitSample:2
methodWithImplicitArg called:Sample:1
methodWithImplicitArg called:Sample:2

implicit

暗黙のパラメータ

implicitとマークされた引数は、その型と一致し、implicitとマークされたオブジェクトが存在すれば自動的に供給される。

object ImplicitTest {

  class Sample(value: Int) {
    override def toString = { "Sample:" + value }
  }

  // 暗黙的に供給されるオブジェクト。implicitを記述する
  implicit val toBeImplicitArg = new Sample(1);

  // implicitとマークされた引数を持つメソッド。implicitを記述する。
  def methodWithImplicitArg(implicit s: Sample) {
    println("methodWithImplicitArg called:" + s)
  }

  def main(args: Array[String]) {
    methodWithImplicitArg // 暗黙的に供給
    methodWithImplicitArg(new Sample(2)) // 明示的に供給
    // methodWithImplicitArg() ... この場合、()をつけてはだめ。引数が不足と言われてしまう。
  }
}

この結果は

methodWithImplicitArg called:Sample:1
methodWithImplicitArg called:Sample:2