是否可以编写具有不同实现的类型类?

Is it possible to write typeclass with different implementations?

这是我之前

的后续

假设我有一个特征ConverterTo两个实现:

trait ConverterTo[T] {
  def convert(s: String): Option[T]
}

object Converters1 {
  implicit val toInt: ConverterTo[Int] = ???
}

object Converters2 {
  implicit val toInt: ConverterTo[Int] = ???
}

我还有两个类A1A2

class A1 {
  def foo[T](s: String)(implicit ct: ConverterTo[T]) = ct.convert(s) 
}

class A2 {
  def bar[T](s: String)(implicit ct: ConverterTo[T]) = ct.convert(s)
}

现在我希望任何 foo[T] 调用都使用 Converters1 并且任何 bar[T] 调用都使用 Converters2 而无需 导入客户端代码中的 Converters1Converters2

val a1 = new A1()
val a2 = new A2()
...
val i = a1.foo[Int]("0") // use Converters1 without importing it
...
val j = a2.bar[Int]("0") // use Converters2 without importing it

可以用 Scala 完成吗?

在 class 中导入 Converters

class A1 {
 import Converters1._
 private def fooPrivate[T](s: String)(implicit ct: ConverterTo[T]) = ct.convert(s) 
 def fooShownToClient[T](s: String) = fooPrivate(s)
}

然后使用给客户端显示的方法

val a1 = new A1()
a1.fooShownToClient[Int]("0")

现在客户端不知道转换器。

如果您遇到需要更多本地控制的情况;您可以选择 implicit 参数 显式 :

val i = a1.foo("0")(Converters1.toInt)
val j = a2.foo("0")(Converters2.toInt)

这真的取决于你想要什么。如果你想 select 一个特定的实现而不污染本地范围,那么就这样做(或引入一个新的范围)。 mohit 的解决方案在 类 需要 特定实现时效果很好(尽管在那种情况下,将此依赖项声明为 implicit)。