当我在 Scala 中有一个函数时:
def toString[T: Show](xs: T*): String = paths.map(_.show).mkString
Run Code Online (Sandbox Code Playgroud)
以及范围内的以下类型类实例:
implicit val showA: Show[MyTypeA]
implicit val showB: Show[MyTypeB]
Run Code Online (Sandbox Code Playgroud)
我可以通过toString以下方式使用函数:
val a1: MyTypeA
val a2: MyTypeA
val stringA = toString(a1, a2)
val b1: MyTypeB
val b2: MyTypeB
val stringB = toString(b1, b2)
Run Code Online (Sandbox Code Playgroud)
但我不能叫toString混合型的参数MyTypeA和MyTypeB:
// doesn't compile, T is inferred to be of type Any
toString(a1, b1)
Run Code Online (Sandbox Code Playgroud)
是否有可能以toString一种可以混合不同类型的参数(但仅限于Show类型类可用)的方式重新定义?
请注意,我知道 cat show interpolator 可以解决这个特定的例子,但我正在寻找一种也可以应用于不同情况的解决方案(例如toNumber)。
我也知道通过.show在将参数传递给toString …