Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><a href="http://www.scala-lang.org/node/112" rel="nofollow noreferrer">Extractors</a> which allow you to replace messy <code>if-elseif-else</code> style code with patterns. I know that these are not exactly <em>hidden</em> but I've been using Scala for a few months without really understanding the power of them. For (a long) example I can replace:</p> <pre><code>val code: String = ... val ps: ProductService = ... var p: Product = null if (code.endsWith("=")) { p = ps.findCash(code.substring(0, 3)) //e.g. USD=, GBP= etc } else if (code.endsWith(".FWD")) { //e.g. GBP20090625.FWD p = ps.findForward(code.substring(0,3), code.substring(3, 9)) } else { p = ps.lookupProductByRic(code) } </code></pre> <p>With this, which is <strong>much</strong> clearer in my opinion</p> <pre><code>implicit val ps: ProductService = ... val p = code match { case SyntheticCodes.Cash(c) =&gt; c case SyntheticCodes.Forward(f) =&gt; f case _ =&gt; ps.lookupProductByRic(code) } </code></pre> <p>I have to do a bit of legwork in the background...</p> <pre><code>object SyntheticCodes { // Synthetic Code for a CashProduct object Cash extends (CashProduct =&gt; String) { def apply(p: CashProduct) = p.currency.name + "=" //EXTRACTOR def unapply(s: String)(implicit ps: ProductService): Option[CashProduct] = { if (s.endsWith("=") Some(ps.findCash(s.substring(0,3))) else None } } //Synthetic Code for a ForwardProduct object Forward extends (ForwardProduct =&gt; String) { def apply(p: ForwardProduct) = p.currency.name + p.date.toString + ".FWD" //EXTRACTOR def unapply(s: String)(implicit ps: ProductService): Option[ForwardProduct] = { if (s.endsWith(".FWD") Some(ps.findForward(s.substring(0,3), s.substring(3, 9)) else None } } </code></pre> <p>But the legwork is worth it for the fact that it separates a piece of business logic into a sensible place. I can implement my <code>Product.getCode</code> methods as follows..</p> <pre><code>class CashProduct { def getCode = SyntheticCodes.Cash(this) } class ForwardProduct { def getCode = SyntheticCodes.Forward(this) } </code></pre>
    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. 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