Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
<build.sbt>
scalaVersion := "2.13.0"
libraryDependencies ++= Seq(
"com.sksamuel.avro4s" %% "avro4s-core" % "3.0.1",
"eu.timepit" %% "refined" % "0.9.9",
"io.scalaland" %% "chimney" % "0.3.2"
)
<plugins.sbt>
addSbtPlugin("com.julianpeeters" % "sbt-avrohugger" % "2.0.0-RC19")
*/
package test01
import test.avro4s.{json => avro}
import eu.timepit.refined.api.Refined
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.refineMV
import io.scalaland.chimney.dsl._
import io.scalaland.chimney.Transformer
object Main01 {
case class Amount(value: Double) extends AnyVal
type Name = String Refined NonEmpty
sealed trait VegetarianType
object VegetarianType {
case object None extends VegetarianType
case object Vegetarian extends VegetarianType
case object Vegan extends VegetarianType
}
case class Ingredient(
name: Name,
sugar: Amount,
fat: Amount
)
case class Pizza(
name: Name,
ingredients: List[Ingredient],
calories: Int,
vegetarianType: VegetarianType = VegetarianType.None
)
val domainPizza = Pizza(
name = refineMV("pepperoni"),
ingredients = List(//| name | sugar | fat
Ingredient(refineMV("pepperoni"), Amount(12), Amount(4.4)),
Ingredient(refineMV("onions"), Amount(1), Amount(0.4))
),
calories = 98
)
val avroPizza1 = avro.Pizza(
name = domainPizza.name.value,
ingredients = domainPizza.ingredients.map { i =>
avro.Ingredient(
name = i.name.value,
sugar = i.sugar.value,
fat = i.fat.value)
},
calories = domainPizza.calories,
vegetarian = domainPizza.vegetarianType != VegetarianType.None,
vegan = domainPizza.vegetarianType == VegetarianType.Vegan
)
implicit val nameToString: Transformer[Name, String] = _.value
val avroPizza2 = domainPizza.into[avro.Pizza]
.withFieldComputed(_.vegetarian, _.vegetarianType != VegetarianType.None)
.withFieldComputed(_.vegan, _.vegetarianType == VegetarianType.Vegan)
.transform
def main(args: Array[String]): Unit = {
println(avroPizza1)
println(avroPizza2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment