Note that there are some explanatory texts on larger screens.

plurals
  1. PODSL for safe navigation operator in Scala
    primarykey
    data
    text
    <p>I want to build a Scala DSL to convert from a existing structure of Java POJOs to a structure equivalent to a Map.</p> <p>However the incoming objects structure is very likely to contain a lot of null references, which will result in no value in the output map.</p> <p>The performance is very important in this context so I need to avoid both reflection and throw/catch NPE.</p> <p>I have considered already <a href="https://stackoverflow.com/questions/1163393/best-scala-imitation-of-groovys-safe-dereference-operator">this topic</a> which does not meet with my requirements.</p> <p>I think the answer may lie in the usage of macros to generate some special type but I have no experience in the usage of scala macros.</p> <p>More formally :</p> <p>POJO classes provided by project : (there will be like 50 POJO, nested, so I want a solution which does not require to hand-write and maintain a class or trait for each of them)</p> <pre><code> case class Level1( @BeanProperty var a: String, @BeanProperty var b: Int) case class Level2( @BeanProperty var p: Level1, @BeanProperty var b: Int) </code></pre> <p>expected behaviour :</p> <pre><code> println(convert(null)) // == Map() println(convert(Level2(null, 3))) // == Map("l2.b" -&gt; 3) println(convert(Level2(Level1("a", 2), 3))) // == Map(l2.p.a -&gt; a, l2.p.b -&gt; 2, l2.b -&gt; 3) </code></pre> <p>correct implementation but I want an easier DSL for writing the mappings</p> <pre><code> implicit def toOptionBuilder[T](f: =&gt; T) = new { def ? : Option[T] = Option(f) } def convert(l2: Level2): Map[String, _] = l2? match { case None =&gt; Map() case Some(o2) =&gt; convert(o2.p, "l2.p.") + ("l2.b" -&gt; o2.b) } def convert(l1: Level1, prefix: String = ""): Map[String, _] = l1? match { case None =&gt; Map() case Some(o1) =&gt; Map( prefix + "a" -&gt; o1.a, prefix + "b" -&gt; o1.b) } </code></pre> <p>Here is how I want to write with a DSL :</p> <pre><code> def convertDsl(l2:Level2)={ Map( "l2.b" -&gt; l2?.b, "l2.p.a" -&gt; l2?.l1?.a, "l2.p.b" -&gt; l2?.l1?.b ) } </code></pre> <p>Note that it is perfectly fine for me to specify that the property is optional with '?'. What I want is to generate statically using a macro a method l2.?l1 or l2?.l1 which returns Option[Level1] (so type checking is done correctly in my DSL).</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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