joesan
joesan

Reputation: 15385

Create dynamic function name on the fly in Scala

I have an object in which I have a bunch of implicit functions. I now want to have some implicits defined for several date formats: For example.,

val dateFormats = Seq("dd/MM/yyyy", "dd.MM.yyyy")

I want to go over this list and generate a function like this:

  dateFormats foreach {
    case dateFormat =>
      implicit def ???: CsvFieldReader[DateTime] = (s: String) => Try {
        DateTimeFormat.forPattern(dateFormat).parseDateTime(s)
      }
  }

How can I resolve the function name? I want the function name to be unique for each entry in the List!

Any ideas? Can I do this with macros?

Upvotes: 0

Views: 154

Answers (2)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

If you create several implicits of the same type CsvFieldReader[DateTime] they will make ambiguity and implicits will not resolve.

Names of implicits don't matter (almost), their types do.

Upvotes: 4

joesan
joesan

Reputation: 15385

So, here is an implementation that works, even though it looks ugly!

implicit def dateTimeCSVConverter: CsvFieldReader[DateTime] = (s: String) => Try {
    dateFormats.map {
      case format => try {
        Some(DateTimeFormat.forPattern(format).parseDateTime(s))
      } catch {
        case _: IllegalArgumentException =>
          println(s"Date format $format incompatible, will try the next available format")
          None
      }
    }.distinct.collectFirst {
      case elem if elem.isDefined => elem.get
    }.get
  }

Upvotes: 0

Related Questions