隐式 class 也可以是动态的吗?
Can implicit class also be Dynamic?
我试图通过执行以下操作将动态功能隐式添加到 class:
case class C(map: Map[String, String])
implicit class Enhancer(c: C) extends Dynamic {
def selectDynamic(str: String) = c.map.getOrElse(str, "")
}
val c = C(Map("a" -> "A"))
这不会编译
val up = c.a
但显式调用将:
val up = Enhancer(c).a
这是为什么?
是的,这将编译...
val up = Enhancer(c).a //up: String = A
...但是,这也会...
val up = Enhancer(c).wxyz //up: String = ""
如果classC
没有成员a
,classEnhancer
没有成员a
,编译器不会检查 a
是否被动态支持,因为 一切 都是动态支持的。
如果我正在设计 language/compiler,它会在允许 a.anything
(因为 Enhancer
是 Dynamic
)之间做出选择,或者只允许本地支持的成员(忽略动态),我想我会选择后者。
the specification中的规则是
Selection on Dynamic
If none of the previous conversions applies, and e
is a prefix of a selection e.x
, and e
's type conforms to class scala.Dynamic
, then the selection is rewritten according to the rules for dynamic member selection.
Conformance 不包含“可以隐式转换”;所以不,你不能隐式添加 Dynamic
。您可以为 Scala 的某些未来版本提出它,但如果它被接受,我会感到惊讶。
我试图通过执行以下操作将动态功能隐式添加到 class:
case class C(map: Map[String, String])
implicit class Enhancer(c: C) extends Dynamic {
def selectDynamic(str: String) = c.map.getOrElse(str, "")
}
val c = C(Map("a" -> "A"))
这不会编译
val up = c.a
但显式调用将:
val up = Enhancer(c).a
这是为什么?
是的,这将编译...
val up = Enhancer(c).a //up: String = A
...但是,这也会...
val up = Enhancer(c).wxyz //up: String = ""
如果classC
没有成员a
,classEnhancer
没有成员a
,编译器不会检查 a
是否被动态支持,因为 一切 都是动态支持的。
如果我正在设计 language/compiler,它会在允许 a.anything
(因为 Enhancer
是 Dynamic
)之间做出选择,或者只允许本地支持的成员(忽略动态),我想我会选择后者。
the specification中的规则是
Selection on Dynamic
If none of the previous conversions applies, and
e
is a prefix of a selectione.x
, ande
's type conforms to classscala.Dynamic
, then the selection is rewritten according to the rules for dynamic member selection.
Conformance 不包含“可以隐式转换”;所以不,你不能隐式添加 Dynamic
。您可以为 Scala 的某些未来版本提出它,但如果它被接受,我会感到惊讶。