[英]Why does the name of an implicit seem to affect its scope resolution in this example?
I am writing a simple JSON serializer for java.io.File
just stingifying the path: 我正在为
java.io.File
编写一个简单的JSON序列化程序,只是指明了路径:
import java.io.File
import play.api.libs.json._
import Implicits.File._
object Implicits {
object File {
implicit val format: Format[File] = new Format[File] {
override def writes(o: File): JsValue = JsString(o.toString)
override def reads(js: JsValue): JsResult[File] = js.validate[String].map(f => new File(f))
}
}
}
final case class Bar(path: File)
object Bar {
implicit val format: Format[Bar] = Json.format
}
I find that the above does not work: 我发现上述方法不起作用:
No instance of play.api.libs.json.Format is available for java.io.File in the implicit scope
However, if I change the name of Implicit.File.format
to Implicit.File.fmt
, it works fine. 但是,如果我将
Implicit.File.format
的名称更改为Implicit.File.fmt
,则可以正常工作。
Why does the name collide in this case when it should be the type , Format[File]
, that the implicit scope resolver should care about? 在这种情况下,为什么名称应该是隐式作用域解析程序应注意的类型
Format[File]
,但为什么会发生冲突?
I'm using play-json 2.6.7. 我正在使用play-json 2.6.7。
Why does the name collide in this case when it should be the type,
Format[File]
, that the implicit scope resolver should care about?在这种情况下,为什么名称应该是隐式作用域解析程序应关注的类型
Format[File]
,但为什么会发生冲突?
Because it does care about the name as well. 因为它也确实在乎名称。
The actual arguments that are eligible to be passed to an implicit parameter of type T fall into two categories.
可以传递给类型T的隐式参数的实际参数分为两类。 First, eligible are all identifiers x that can be accessed at the point of the method call without a prefix and that denote an implicit definition or an implicit parameter.
首先,合格的所有标识符x都可以在方法调用时访问而没有前缀 ,并且表示隐式定义或隐式参数。 An eligible identifier may thus be a local name, or a member of an enclosing template, or it may be have been made accessible without a prefix through an import clause.
因此,合格的标识符可以是本地名称,也可以是封闭模板的成员,或者可以通过import子句使该标识符不带前缀就可以访问。
At the line implicit val format: Format[Bar] = Json.format
, format
means Bar.format
and not Implicits.File.format
, so Implicits.File.format
isn't eligible as an implicit by this rule. 在
implicit val format: Format[Bar] = Json.format
, format
表示Bar.format
而不是Implicits.File.format
,因此Implicits.File.format
不符合此规则的隐式条件。 And it isn't in a companion object, so it isn't covered by the second category either. 而且它不在同伴对象中,因此它也不在第二类中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.