Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could do this with runtime reflection, and I'm sure you'll get answers telling you how, if you want that, but this is actually a neat use case for <a href="http://scalamacros.org/" rel="nofollow noreferrer">Scala 2.10's macros</a>, so here goes. First assume we have a file named <code>ParamMapMaker.scala</code>:</p> <pre><code>object ParamMapMaker { def paramMap: Map[String, Any] = macro paramMapImpl def paramMapImpl(c: scala.reflect.macros.Context) = { import c.universe._ val params = c.enclosingMethod match { case DefDef(_, _, _, ps :: Nil, _, _) =&gt; ps.map(p =&gt; reify(( c.Expr[String](Literal(Constant(p.name.decoded))).splice, c.Expr[Any](Ident(p.symbol)).splice )).tree ) case _ =&gt; c.abort(c.enclosingPosition, "Can't call paramMap here!") } c.Expr[Map[String, Any]](Apply(Select(Ident("Map"), "apply"), params)) } } </code></pre> <p>I'll leave snake casing the map keys as an (easy) exercise for the reader.</p> <p>We also have a test file (named <code>Test.scala</code>):</p> <pre><code>object Test extends App { def foo(hello: String, answer: Int) = ParamMapMaker.paramMap println(foo("world", 42)) } </code></pre> <p>Now we compile both of these:</p> <pre><code>scalac -language:experimental.macros ParamMapMaker.scala scalac Test.scala </code></pre> <p>And when we run <code>Test</code> we'll get the following:</p> <pre><code>Map(hello -&gt; world, answer -&gt; 42) </code></pre> <p>The nifty thing about this is that there's none of the overhead of runtime reflection. If we compile the test file with <code>-Ymacro-debug-verbose</code>, we see that the following code has been generated (in effect) for the body of <code>foo</code> at compile time:</p> <pre><code>Map.apply[String, Any]( scala.Tuple2.apply[String, String]("hello", hello), scala.Tuple2.apply[String, Int]("answer", answer) ) </code></pre> <p>Exactly as we'd expect.</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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