嵌套扩展方法不起作用 - Scala

时间:2015-11-15 16:01:31

标签: scala extension-methods dsl implicit-conversion implicit

我创建了一个简单的Date DSL。我的代码是:

import java.time.{Year, LocalDate}

import Numeric.Implicits._

object Main {

  implicit def wrapMonth[A:Numeric](v: A) = new {
    def october = {
      def of(y: Integer) = {
        5
      }
      9
    }
  }

  def main(args:Array[String]): Unit =
  {
    println(3.october of 2014)
  }
}

我有错误:

value of is not a member of Int
    println(3.october of 2014)

我不明白,为什么会发生这种错误,以及如何修复它。

1 个答案:

答案 0 :(得分:2)

以下工作,

implicit def wrapMonth[A: Numeric](v: A) = new {
    def october = {
      9
    }
    def of(y: Integer) = {
      5
    }
  }

您无法从外部调用嵌套方法。它不可见。

修改

implicit def wrapMonth(v: Int) = new {
  def october = {
    (v, 9)
  }
}

implicit def wrapDay(v: (Int, Int)) = new {
  def of(y: Int) = {
    val c = Calendar.getInstance()
    c.set(y, v._2, v._1, 0, 0)
    c.getTime
  }
}