When I am reading Scala reflection tutorial. I found a syntax very wired as follows.
import scala.reflect.runtime.universe._
typeOf[List[_]].member("map": TermName)
So the member
function takes Name
type parameter, and then "map": TermName
is passed into it. What does this syntax exactly mean? I am guessing it is sugar shortcut for .member(TermName("map"))
.
This syntax is called type ascription:
Ascription is basically just an up-cast performed at compile-time for the sake of the type checker.
It is used here because the signature of member
is
def member(name: Name): Symbol
so it is expecting input of type Name
hence
typeOf[List[_]].member("map")
gives error because "map"
is not Name
. Providing type ascription "map": Name
triggers implicit conversion
typeOf[List[_]].member(stringToTermName("map"): TermName)
however the same can be achieved with more explicit
typeOf[List[_]].member(TermName("map"))
The implicit conversion stringToTermName
technique is deprecated
/** 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)