Search code examples
scalaextension-methodsdslimplicit-conversionimplicit

Nested Extension Method does not work - Scala


I create a simply Date DSL. My code is:

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

I have the error:

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

I dont understand, why this error happens, and how to fix it.


Solution

  • Following will work,

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

    You cant call a nested method from outside. Its not visible.

    Edit

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