简体   繁体   English

伴侣对象的Scala隐式逻辑

[英]Scala implicit logic for companion objects

object Test extends App {

  def print(s: String)(implicit p: Prefixer) = {
    println(p.prefix + s)
  }

  print("test")

}

case class Prefixer(prefix: String)

object Prefixer {
  implicit val p = Prefixer("***")
}

The above code does not compile, because the compiler is not able to find an implicit value for Prefixer. 上面的代码无法编译,因为编译器无法找到Prefixer的隐式值。 However, if I put the case class Prefixer and the companion object in another file it works. 但是,如果将案例类Prefixer和伴随对象放在另一个文件中,它将起作用。 Why is that? 这是为什么?

It is to do with the order of declaration. 这与声明的顺序有关。 It also works if you just move the Prefixer and its companion above the main object. 如果仅将Prefixer及其同伴移动到主要对象上方,它也将起作用。 When the class is in another file, the compiler can scan that file first & then come to the file implementing the App. 当该类位于另一个文件中时,编译器可以先扫描该文件,然后进入实现该应用程序的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM