【问题标题】:Compiler cannot find an implicit defined in a companion object编译器找不到伴随对象中定义的隐式定义
【发布时间】:2019-10-11 14:10:42
【问题描述】:

我有一个定义特征及其伴随对象的文件。

trait SomeTrait {
}

object SomeTrait extends SomeConfig {
 implicit def intToString(v: Int): String = v.toString
}

在另一个文件中,我有一个案例类,它扩展了上面的特征。

case class SomeCaseClass extends AnotherTrait with SomeTrait {

  protected def someLoginc(): Unit = {
   // The compiler cannot find the implicit def intToString 
  }
}

编译器怎么找不到伴生对象中定义的隐式?

根据我的理解,伴随对象中定义的隐式会自动带入范围。

【问题讨论】:

    标签: scala


    【解决方案1】:

    根据我的理解,伴生对象中定义的隐式会自动带入范围。

    不,编译器会查看转换中涉及的类型的伴随对象及其部分。例如。在Where does Scala look for implicits? Companion Objects of a Type:

    首先,查找“源”类型的伴生对象...其次,查找预期类型的​​伴生对象...注意,超类的伴生对象也会被查找...

    即要使此规则适用于 intToString,它需要在 IntString 或它们的超类型之一的伴随对象中声明(当然你不能这样做)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2021-02-12
      相关资源
      最近更新 更多