Where does Scala look for implicits?

前端 未结 2 600
傲寒
傲寒 2020-11-21 16:12

An implicit question to newcomers to Scala seems to be: where does the compiler look for implicits? I mean implicit because the question never seems to get fully fo

2条回答
  •  后悔当初
    2020-11-21 16:54

    I wanted to find out the precedence of the implicit parameter resolution, not just where it looks for, so I wrote a blog post revisiting implicits without import tax (and implicit parameter precedence again after some feedback).

    Here's the list:

    • 1) implicits visible to current invocation scope via local declaration, imports, outer scope, inheritance, package object that are accessible without prefix.
    • 2) implicit scope, which contains all sort of companion objects and package object that bear some relation to the implicit's type which we search for (i.e. package object of the type, companion object of the type itself, of its type constructor if any, of its parameters if any, and also of its supertype and supertraits).

    If at either stage we find more than one implicit, static overloading rule is used to resolve it.

提交回复
热议问题