Let's say we have two case classes Woof & Meow
case class Meow(a: String, b: String)
case class Woof(a: String, b: String)
And we would like to create a function foo that concatenates a with b and works generically (kind-of) for both/either Woof & Meow like:
def foo[T](meowOrWoof: T) = meowOrWoof.a + meowOrWoof.b
Of course that will not compile as neither a nor b are parameters of T.
One thing I have tried, is to create a trait like:
trait Pets[T] {
def foo[T](someClass: T): String
}
case class Meow(a: String, b: String) extends Pets[Meow] {
override def foo[T](someClass: T) = a + b
}
case class Woof(a: String, b: String) extends Pets[Woof] {
override def foo[T](someClass: T) = a + b
}
But here we have to create the function multiple times even though it has the same implementation.
Is there another way we can create the function foo that works for both Meow & Woof, and concatenates a with b for either?