Question

I have a type resultType of Context.this.type#c#universe#Type. I need to match it against Unit type. I tried

resultType match {
  case q"Unit" => ...
}

but I suppose that Unit is just a string literal here that obviously do not match. How to match types via quasiqotes?

And I also tried

resultType match {
  case TypeRef(ThisType(_), Symbol("scala.Unit"), _) => ...
}

but have an error:

[error]  pattern type is incompatible with expected type;
[error]  found   : Symbol
[error]  required: Context.this.c.universe.SymbolContextApi

How to match a type in that way?

Was it helpful?

Solution

The primary reason why quasiquotes don't work in this case is the fact that you don't match on a Tree but rather a Type. These two are separate concepts of the reflection API that are not quite the same.

A simple way to check if type is the same as the one you expect is to use typeOf and type equality operator =:=:

case tpe if tpe =:= typeOf[Unit] =>

Of course this is not the only way. One can also match through TypeRef and check for equality of symbols inside of it as shown in other answers.

OTHER TIPS

A variation on your answer, debatable if it is any better:

case TypeRef(_, sym, _) if sum == typeOf[Unit].typeSymbol => ...

Alas, I found nothing smarter than this:

case TypeRef(_, sym, _) if sym.fullName == "scala.Unit" => ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top