Reputation: 651
for example, I have case classes
case class foo(timestamp:String, epochSecond: Long)
and
case class bar(epochSecond: Long, timestamp:String)
Is it possible to make conversion between the instance of these two classes?
Upvotes: 0
Views: 45
Reputation: 51271
Your question is rather vague because there are so many ways to accomplish this. Here's one option.
With the definition of the case classes ...
case class Foo(timestamp:String, epochSecond: Long)
case class Bar(epochSecond: Long, timestamp:String)
... add auxiliary factory methods.
object Foo {
def apply(b: Bar): Foo = this(b.timestamp, b.epochSecond)
}
object Bar {
def apply(f: Foo): Bar = this(f.epochSecond, f.timestamp)
}
Now you can transition from one type to the other very simply.
val fooX = Foo("noon", 42L)
val barY = Bar(99L, "none")
val fooY = Foo(barY) //fooY: Foo = Foo(none,99)
val barX = Bar(fooX) //barX: Bar = Bar(42,noon)
Upvotes: 1