Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Postfix vs Infix</strong></p> <p>Let's first look at how infix and postfix notation relate to each other. Given your case when you write <code>Num(0) | inc</code> then that is equivalent to <code>Num(0).|(inc)</code> in postfix notation.</p> <p>So looking at your desired syntax:</p> <pre><code>Num(0) | inc | inc </code></pre> <p>This will be equivalent to the following in postfix notation:</p> <pre><code>Num(0).|(inc).|(inc) </code></pre> <p>Ok, now that that's clear let's do this!</p> <p><strong>The solution</strong></p> <p>The <code>def |</code> needs to take a parameter, that holds the function it should do. There are two solutions here, either we define a function over <code>Num</code> or we define a function over the <code>Int</code> the <code>Num</code> is actually holding:</p> <pre><code>implicit class Pipe(n:Num){ def |(fn: (Num) =&gt; Num) = fn(n) def |(fn: (Int) =&gt; Int) = Num(fn(n.n)) } </code></pre> <p>Both would work - you need to choose which one will work best for you.</p> <p>Now that we have this, we need to define this function. You could put this in <code>Num</code>'s companion object (also providing the two differing implementations):</p> <pre><code>object Num { val incNum: Num =&gt; Num = n =&gt; Num(n.n + 1) val inc = (i: Int) =&gt; i + 1 } </code></pre> <p>Looks like we're done. Now we just need to import these functions from the object and use them. The whole code:</p> <pre><code>case class Num(n:Int) object Num { val incNum: Num =&gt; Num = n =&gt; Num(n.n + 1) val inc = (i: Int) =&gt; i + 1 } implicit class Pipe(n:Num){ def |(fn: (Num) =&gt; Num) = fn(n) def |(fn: (Int) =&gt; Int) = Num(fn(n.n)) } import Num._ Num(0) | inc | inc // Num(2) Num(0) | incNum | incNum // Num(2) </code></pre>
    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.
    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.
 

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