Skip to content

Add custom mapper for snake case to camel case #831

@akreit

Description

@akreit

Checklist

Describe the desired behavior

I came across a case where I wanted to transform case class objects with camelCase member names into case class objects with snake case member names.
After researching a bit I came across this discussion and the related PR: #89

The related PR pointed me to the docs: https://chimney.readthedocs.io/en/stable/supported-transformations/#defining-custom-name-matching-predicate

With that, I implemented a mapper which works well enough:

case object CamelSnakeCaseEquality extends TransformedNamesComparison {
  def namesMatch(fromName: String, toName: String): Boolean = {
    val snakeCase = fromName
      .flatMap { c =>
        if (c.isUpper) Seq('_', c.toLower)
        else Seq(c)
      }
      .mkString
    snakeCase == toName
  }
}

Unless any of the existing extensions of TransformedNamesComparison already provide this functionality (which I could not find), I imagine this to be a common enough case to come with chimney out of the box.

Any opinions on this?

PS: I'd be happy to raise a PR for this.

Use case example

case class UserDAO(userId, createdAt)
case class UserDTO(user_id, created_at)

UserDAO(123, "2024-12-03T12:00:00")
   .into[UserDTO]
   .enableCustomFieldNameComparison(
        CamelSnakeCaseEquality
   )
   .transform

How it relates to existing features

Yes, as stated above, this can be (self) implemented using existing functionality.

Additional context

Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions