Search code examples
scalascala-2.10

How to determine a type alias with Scala Reflection?


With Scala Reflection in 2.10, how can one determine if a type is a type alias?

The following does not work:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> typeOf[String].typeSymbol.asType.isAliasType
res46: Boolean = false

Solution

  • This is a bug: https://issues.scala-lang.org/browse/SI-6474 caused by the fact that Type.typeSymbol automatically dereferences aliases.

    scala> showRaw(typeOf[String])
    res0: String = TypeRef(SingleType(ThisType(scala), scala.Predef), newTypeName("String"), List())
    
    scala> typeOf[String].typeSymbol
    res1: reflect.runtime.universe.Symbol = class String
    
    scala> typeOf[String].typeSymbol.asType.isAliasType
    res2: Boolean = false
    
    scala> val TypeRef(_, sym, _) = typeOf[String]
    sym: reflect.runtime.universe.Symbol = type String
    
    scala> sym.asType.isAliasType
    res3: Boolean = true
    

    A workaround, as partially provided by the REPL printout, is to perform manual pattern matching and extract the underlying symbol. An alternative is to cast to scala.reflect.internal.Types#Type and use typeSymbolDirect.