When I have a function in Scala:
def toString[T: Show](xs: T*): String = paths.map(_.show).mkString
And the following type class instances in scope:
implicit val showA: Show[MyTypeA]
implicit val showB: Show[MyTypeB]
I can use function toString
in the following ways:
val a1: MyTypeA
val a2: MyTypeA
val stringA = toString(a1, a2)
val b1: MyTypeB
val b2: MyTypeB
val stringB = toString(b1, b2)
But I cannot call toString
mixing parameters of type MyTypeA
and MyTypeB
:
// doesn't compile, T is inferred to be of type Any
toString(a1, b1)
Is it possible to redefine toString
in such a way that it becomes possible to mix parameters of different types (but only for which a Show
typeclass is available)?
Note that I am aware of the cats show interpolator which solves this specific example, but I'm looking for a solution which can be applied to different cases as well (e.g. toNumber
).
I am also aware of circumventing the problem by calling .show
on the parameters before passing them to the toString
function, but I'm looking for a way to avoid this as it results in code duplication.
.show
on every argument before passing it, as it was least intrusive. – Tc