【问题标题】:How to fix this typeclass example?如何修复这个类型类示例?
【发布时间】:2015-04-01 10:14:26
【问题描述】:

这是我之前question的后续:

假设我创建了以下测试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 typeclass


    【解决方案1】:

    class A 中的import Converters._ 不会剪切它。您可以删除它,代码仍将编译。编译器需要在实际隐式中找到的那一刻不在class A 中,其中foo 刚刚声明。

    当您调用 REPL 中的 a.foo[Int](..) 时,编译器需要在隐式范围内找到 ConverterTo[Int]。所以这就是需要导入的地方。

    如果 object Converterstrait ConverterTo 被命名为相同(因此会有一个伴随对象),则不需要导入。

    【讨论】:

    • 谢谢。现在很明显我需要导入,我打电话给a.foo[Int] :) 我希望我终于明白了。
    • 至于伴生对象:恐怕不能用。我的问题是我需要ConvertersTo 的两种不同实现才能在两个不同的类A1A2 中使用,它们定义了问题中的foo。我可能会发布另一个关于它的问题。
    猜你喜欢
    • 2021-02-17
    • 2016-06-15
    • 2020-10-04
    • 2017-10-12
    • 2016-01-13
    • 1970-01-01
    • 2019-12-16
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多