Scala 如何修复这个typeclass示例?
这是我之前的后续行动: 假设我创建以下测试Scala 如何修复这个typeclass示例?,scala,typeclass,Scala,Typeclass,这是我之前的后续行动: 假设我创建以下测试converter.scala: trait ConverterTo[T] { def convert(s: String): Option[T] } object Converters { implicit val toInt: ConverterTo[Int] = new ConverterTo[Int] { def convert(s: String) = scala.util.Try(s.toInt).toOpti
converter.scala
:
trait ConverterTo[T] {
def convert(s: String): Option[T]
}
object Converters {
implicit val toInt: ConverterTo[Int] =
new ConverterTo[Int] {
def convert(s: String) = scala.util.Try(s.toInt).toOption
}
}
class A {
import Converters._
def foo[T](s: String)(implicit ct: ConverterTo[T]) = ct.convert(s)
}
现在,当我试图在REPL中调用foo
时,它无法编译:
scala> :load converter.scala
Loading converter.scala...
defined trait ConverterTo
defined module Converters
defined class A
scala> val a = new A()
scala> a.foo[Int]("0")
<console>:12: error: could not find implicit value for parameter ct: ConverterTo[Int]
a.foo[Int]("0")
^
scala>:load converter.scala
正在加载转换器。scala。。。
定义特征转换器
定义模块转换器
定义的A类
scala>val a=new a()
scala>a.foo[Int](“0”)
:12:错误:找不到参数ct:ConverterTo[Int]的隐式值
a、 foo[Int](“0”)
^
导入转换器。
A类中的不会切断转换器。您可以删除它,代码仍将编译。编译器需要在实际隐式中查找的时刻不在class A
中,其中刚刚声明了foo
在调用REPL中的a.foo[Int](..)
时,编译器需要在隐式作用域中找到一个ConverterTo[Int]
。因此,这就是需要导入的地方
如果
对象转换器
和特征转换器的名称相同(因此将有一个伴生对象),则不需要导入 多谢各位。现在很明显,我需要导入,在这里我调用a.foo[Int]
:)我希望我最终得到了它。我的问题是,我需要两个不同的ConvertersTo
实现,以便在两个不同的类A1
和A2
中使用,这两个类定义了foo
。我可能会发布另一个关于它的问题。