Note that there are some explanatory texts on larger screens.

plurals
  1. POStatic return type of Scala macros
    primarykey
    data
    text
    <p>So I've got this macro:</p> <pre><code>import language.experimental.macros import scala.reflect.macros.Context class Foo class Bar extends Foo { def launchMissiles = "launching" } object FooExample { def foo: Foo = macro foo_impl def foo_impl(c: Context): c.Expr[Foo] = c.Expr[Foo](c.universe.reify(new Bar).tree) } </code></pre> <p>I've said three times that I want <code>foo</code> to return a <code>Foo</code>, and yet I can do the following (in 2.10.0-RC3):</p> <pre><code>scala&gt; FooExample.foo res0: Bar = Bar@4118f8dd scala&gt; res0.launchMissiles res1: String = launching </code></pre> <p>The same thing happens if I remove the type parameters on either <code>c.Expr</code>. If I really want to make sure that whoever's calling <code>foo</code> can't see that they're getting a <code>Bar</code>, I have to add a type ascription in the tree itself.</p> <p>This is actually pretty great—it means for example that I can point a macro at a schema of some sort and create an anonymous subclass of some <code>Vocabulary</code> class with member methods representing terms in the vocabulary, and these will be available on the returned object.</p> <p>I'd like to understand exactly what I'm doing, though, so I have a couple of questions. First, what is the return type on the <code>foo</code> method actually for? Is it just available for (optional) documentation? It clearly constrains the return type (e.g., I can't change it to <code>Int</code> in this case), and if I remove it entirely I get an error like this:</p> <pre><code>scala&gt; FooExample.foo &lt;console&gt;:8: error: type mismatch; found : Bar required: Nothing FooExample.foo ^ </code></pre> <p>But I <em>can</em> change it to <code>Any</code> and still get a statically typed <code>Bar</code> when I call <code>foo</code>.</p> <p>Second, is this behavior specified somewhere? This seems like a fairly elementary set of issues, but I haven't been able to search up a clear explanation or discussion.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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