如何修复这个类型类示例? [英] How to fix this typeclass example?
问题描述
这是我之前的的后续问题:
假设我创建了以下测试 converter.scala
:
Suppose I create the following test 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
时,它无法编译:
Now when I tried to call foo
in REPL it fails to compile:
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")
^
推荐答案
import Converters._
in class A
没有删减.您可以删除它,代码仍将编译.编译器需要在实际隐式中找到的时刻不在 class A
中,其中 foo
刚刚声明.
import Converters._
in class A
does not cut it. You can remove it and the code will still compile. The moment the compiler needs to find in actual implicit is not in class A
, where foo
is just declared.
在您调用 REPL 中的 a.foo[Int](..)
时,编译器需要在隐式作用域中找到一个 ConverterTo[Int]
.所以这就是需要导入的地方.
The compiler needs to find a ConverterTo[Int]
in implicit scope at the moment you call a.foo[Int](..)
that is in the REPL. So this is where the import needs to be.
如果 object Converters
和 trait ConverterTo
被命名为相同的(所以会有一个伴随对象),将不需要导入.
Had object Converters
and trait ConverterTo
been named the same (so there would be a companion object) the import would not be needed.
这篇关于如何修复这个类型类示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!