如何修复此类型类示例?
How to fix this typeclass example?
这是我之前 :
的后续
假设我创建以下测试 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")
^
import Converters._
in class A
不剪。您可以删除它,代码仍会编译。编译器需要在实际隐式中查找的时刻不在 class A
中,其中刚刚声明了 foo
。
当您在 REPL 中调用 a.foo[Int](..)
时,编译器需要在隐式作用域中找到 ConverterTo[Int]
。所以这就是需要导入的地方。
如果 object Converters
和 trait ConverterTo
被命名为相同的(因此会有一个伴随对象),则不需要导入。
这是我之前
假设我创建以下测试 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")
^
import Converters._
in class A
不剪。您可以删除它,代码仍会编译。编译器需要在实际隐式中查找的时刻不在 class A
中,其中刚刚声明了 foo
。
当您在 REPL 中调用 a.foo[Int](..)
时,编译器需要在隐式作用域中找到 ConverterTo[Int]
。所以这就是需要导入的地方。
如果 object Converters
和 trait ConverterTo
被命名为相同的(因此会有一个伴随对象),则不需要导入。