使用 'value: Type' 语法自动转换类型

Autocasting types using 'value: Type' syntax

当我阅读时Scala reflection tutorial。我发现一个非常有线的语法如下。

  import scala.reflect.runtime.universe._
  typeOf[List[_]].member("map": TermName)

所以member函数接受了Name类型的参数,然后"map": TermName传入了它。这个语法到底是什么意思?我猜这是 .member(TermName("map")) 的快捷方式。

这种语法叫做type ascription:

Ascription is basically just an up-cast performed at compile-time for the sake of the type checker.

这里用是因为member的签名是

def member(name: Name): Symbol

所以它期望输入类型 Name 因此

typeOf[List[_]].member("map")

给出错误,因为 "map" 不是 Name。提供 type ascription "map": Name 触发隐式转换

typeOf[List[_]].member(stringToTermName("map"): TermName)

然而,同样可以通过更明确的方式实现

typeOf[List[_]].member(TermName("map"))

隐式转换 stringToTermName 技术已弃用

  /** An implicit conversion from String to TermName.
   * Enables an alternative notation `"map": TermName` as opposed to `TermName("map")`.
   * @group Names
   */
  @deprecated("use explicit `TermName(s)` instead", "2.11.0")
  implicit def stringToTermName(s: String): TermName = TermName(s)