Scala 隐式参数需要类型注释才能编译

Scala 隐式参数需要类型注释才能编译,scala,implicit,Scala,Implicit,以下是我的测试代码: object ImplicitTest { import JoesPrefs._ Greeter.greet("Joe") // could not find implicit value for parameter prompt: } class PreferredPrompt(val preference: String) object JoesPrefs { implicit val prompt = new PreferredPr

以下是我的测试代码:

object ImplicitTest {
  import JoesPrefs._
  Greeter.greet("Joe") // could not find implicit value for parameter prompt: 
}
class PreferredPrompt(val preference: String)

object JoesPrefs {
  implicit val prompt = new PreferredPrompt("Yes, master> ")
}
object Greeter {
  def greet(name: String)(implicit prompt: PreferredPrompt) = {
    println("Welcome, " + name + ". The system is ready.")
    println(prompt.preference)
  }
}
我使用scala 2.11.12,不知道为什么在将类型注释添加到val之前,此隐式表达式不起作用:

object JoesPrefs {
  implicit val prompt: PreferredPrompt  = new PreferredPrompt("Yes, master> ")
}

因此,确切的内部代码有点疯狂,但基本上可以归结为代码的编译顺序。 添加类型注释时,val比未添加时更快“编译并放入范围”,并且可以在ImplicitTest中解析


有趣的是(至少对我来说^^),你也可以将ImplicitTest移动到JoesPref对象之后的代码行上(或者将其移动到自己的文件中),它将在没有类型注释的情况下编译。

无论如何,隐式值应该总是有显式类型注释。我认为这是一个很好的做法,但不是必须的?在某些情况下,它确实是需要的。在其他情况下,这会有所帮助。在少数情况下,这是不可能的。这是否回答了你的问题?是的,就像你说的那样。你知道有什么地方提到过这种情况吗?语言创建者的评论如下: