Implicit function usage within a case class

Hi,

I have a function ro get the busines date in Localdate format
I have a class A(startDate: String)
{
def parsedStartDate: LocalDate = Dutils.parsedCompactDate(startDate)
}
i use this method in another case class
In this below class B, we convert this startDate to Java.sql.Date format
Case class B(startDate: Date)
Object B
Def apply(a: A) = {
startDate = a.parsedStartDate
}

I have another object within utils package having below method

Object ABC {
Implicit def convertSql( date: LocalDate) : Date = Date.valueOf(date)
}

So my question is how i can use this implicit def in my class B to convert the startDate field from LocalDate to Date in an implicit way.

I tried to use like this, but it looks like this is not the jmplicit way to use the function in scala.
Case class B(startDate: Date)
Object B
Def apply(a: A) = {
startDate = ABC.convertSql(a.parsedStartDate)
}

Could you help me to get the right inplicit way to use the function in class B

THANKS

The reason for this not compiling has nothing to do with implicits:

Your apply method assigns a variable (startDate), that is not in scope at that position. The method in the B object isn’t like a constructor, it has to call the constructor of B itself, i.e. you need either of these:

def apply(a: A) = new B(ABC.convertSql(a.parsedStartDate))
// or, using the autogenerated apply function:
def apply(a: A): B = B(ABC.convertSql(a.parsedStartDate))

In both cases, the convertSql method is called explicitly, so there is no implicit conversion.

Personally, I think that this is fine, implicit conversions make the code harder to understand. But if you want to use convertSql as an implicit conversion, you’ll have to import it into scope:

import ABC.convertSql

def apply(a: A) = new B(a.parsedStartDate)

This will call the method implicitly.

1 Like

Thank you…This really helped…i tried with the implicit way and it worked.