Chris
Chris

Reputation: 99

Scala: Convert nearly identical case classes with value of different type

Say I have a case class of:

case class car1 (
  var wheels: Map[String, String] = Map[String, String](),
  var tire: String = "",
  var window: String = ""
) {}

and I simply want to convert an instance of it into another case class with a single difference in the type of one variable wheels, with all other values the same:

case class car2 (
  var wheels: Array[(String, String)],
  var tire: String = "",
  var window: String = ""
) {}

What is the best way in Scala to: 1. Abstract all boilerplate default values into a single structure 2. convert between the two classes such that a conversion changes the type of the wheels value

I want to convert an instance of car1 into car2 such that a standard conversion function is applied to wheels.

Upvotes: 1

Views: 238

Answers (2)

Dmytro Mitin
Dmytro Mitin

Reputation: 51723

2. Try

case class car1 (
                  var wheels: Map[String, String] = Map[String, String](),
                  var tire  : String              = "",
                  var window: String              = ""
                ) {
  def toCar2: car2 = car2(wheels.toArray, tire, window)
}

1. Try

def default[A](implicit factory: Factory[_, A]): A = factory.newBuilder.result()

case class car1 (
                  var wheels: Map[String, String] = default,
                  var tire  : String              = default,
                  var window: String              = default
                ) {
  def toCar2: car2 = car2(wheels.toArray, tire, window)
}

case class car2 (
                  var wheels: Array[(String, String)] = default,
                  var tire  : String                  = default,
                  var window: String                  = default
                ) {}

Scala 2.13.

Upvotes: 2

pme
pme

Reputation: 14813

I would add an apply function in the companion object of car2:

object car2 {
  def apply(car1: car1): car2 =
     car2(car1.wheels.toArray, car1.tire, car1.window)
}

Usage:

car2(car1(Map("x" -> "a"), "conti", "glass"))

Upvotes: 2

Related Questions