How to match the "universe number" using quasiquadrats or deconstructors?

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

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

but I suppose Unit is just a string literal that clearly doesn't match. How to match types through quasi-goths?

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 type in this way?

+4
source share
3 answers

The main reason quasi-quarters do not work in this case is because you are not matching with Tree , but rather with Type . These two are separate concepts of the reflection API, which are not exactly the same.

An easy way to check if the type is the same as the one you expect is to use typeOf and enter the equality operator =:= :

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

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

+6
source

Variant of your answer, controversial if better:

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

Alas, I did not find anything smarter than this:

 case TypeRef(_, sym, _) if sym.fullName == "scala.Unit" => ... 
-one
source

Source: https://habr.com/ru/post/1501604/


All Articles