Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a `universe#Type` via quasiquotes or deconstructors?

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?

like image 428
Alexander Myltsev Avatar asked Jan 12 '23 10:01

Alexander Myltsev


1 Answers

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.

like image 196
Denys Shabalin Avatar answered Feb 02 '23 21:02

Denys Shabalin