Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何修复这个typeclass示例?_Scala_Typeclass - Fatal编程技术网

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
。我可能会发布另一个关于它的问题。