Skip to content

5. Different transformations for same types in same case class

@dawrutowicz edited this page Jun 8, 2019 · 3 revisions

It's a common case when your domain model contains fields of same types but you would like to transform them using different logic. For example, you would like to represent day, month and year as integers within single model.

cleanframes allows to achieve it by defining value classes and transformations for them.

Let's assume you would like to have two integer types in a case class.

Define new types:

case class Col1(not_relevant: Int) extends AnyVal

case class Col2(not_relevant: Int) extends AnyVal

Use them in a case class:

case class Model(col1: Option[Col1],
                 col2: Option[Col2])

Define implicit transformer functions (for simplicity sake, example is in udf-style):

import java.lang.Integer._

implicit val col1Transformer: String => Col1 = a => Col1(parseInt(a) + 100)
implicit val col2Transformer: String => Col2 = a => Col2(parseInt(a) + 200)

Rest usage of the library remains the same.

These two integers will be transformed with no type-clash.

Full running code example can be found here.

Clone this wiki locally