Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy returning a match from macro gives me type errors?
    text
    copied!<p>Consider this example:</p> <pre><code>class A object Macros { def genA(str: String): A[_] = macro _genA def _genA(c: Context)(str: c.Expr[String]): c.Expr[A[_]] = { import c.universe._ c.Expr[A[_]]( reify { new A[Int] }.tree) } // somewhere in code genA("int") // --&gt; new A[Int] </code></pre> <p>It works as expected. However, when I introduce a match, that selects an expression via match, I get into problems:</p> <pre><code>class A object Macros { def genA(str: String): A[_] = macro _genA def _genA(c: Context)(str: c.Expr[String]): c.Expr[A[_]] = { import c.universe._ c.Expr[A[_]]( Match( str.tree.duplicate, List( CaseDef(Literal(Constant("int")), EmptyTree, reify { new A[Int] }.tree)))) } } // again, somewhere far, far away in the code genA("int") // it expands to ("int" match { case "int" =&gt; new A[Int] }) </code></pre> <p>It compiles fine, but after macro expansion I get this error:</p> <pre><code>found : rsf.macros.A[Int] required: rsf.macros.A[_$1] where type _$1 genA("int") ^ </code></pre> <p>The same expression, when entered manually, compiles fine:</p> <pre><code>val a: A[_] = "int" match { case "int" =&gt; new A[Int] } </code></pre> <p>Why does this happen? Is there a way to fix it?</p> <p><strong>EDIT:</strong></p> <p>I now use the following workaround:</p> <pre><code>class A object Macros { def genA(str: String): A[_] = macro _genA def _genA(c: Context)(str: c.Expr[String]): c.Expr[A[_]] = { import c.universe._ val mtch = c.Expr[A[_]]( Match( str.tree.duplicate, List( CaseDef(Literal(Constant("int")), EmptyTree, reify { new A[Int] }.tree)))) reify { mtch.splice.asInstanceOf[A[_]] } } } </code></pre> <p>But I feel that every time this macro executes, somewhere a kitten dies. Maybe there is some way to spare the kittens?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload