简体   繁体   中英

In Scala how can I reflect on a typedef (eg. type Data = Map[String,Any])?

I'm writing some reflection code. I have a class like this:

case class Foo(
   info : Map[String,Any]
)

I reflect on this class like this:

ctor.typeSignature.paramLists.head.map( f => {
   println("F: "+f.typeSignature)
})

When defined as above I see what I expect for the type of member info: Map[String,scala.Any]

But... if I do this:

type Data = Map[String,Any]
case class Foo(
   info : Data
)

Now I see the type of info as: co.blocke.scalajack.test.v4.Data

How can I tell if a type like Data above is actually a typedef any how can I see what it resolves to? (the type of 'f' in the clip above is universe.Symbol)

I mistakenly thought it was compiler-candy and after compilation it would have resolved to its defined type, but apparently not!

You can use dealias :

type Data = Map[String,Any]
case class Foo(info: Data)

Excuse the lack of safety measures, but to cut to the chase:

typeOf[Foo].typeSymbol
    .asClass
    .primaryConstructor
    .typeSignature
    .paramLists
    .head
    .head
    .typeSignature
    .dealias

res2: reflect.runtime.universe.Type = scala.collection.immutable.Map[String,scala.Any]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM