Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Currying, That's Why</h1> <p>Daniel did a great job at explaining why parameterless methods are necessary. I'll explain why they are regarded distinctly from zero-parameter methods.</p> <p>Many people view the distinction between parameterless and zero-parameter functions as some vague form of syntactic sugar. In truth it is purely an artifact of how Scala supports currying (for completeness, see below for a more thorough explanation of what currying is, and why we all like it so much).</p> <p>Formally, a function may have zero or more parameter lists, with zero or more parameters each.<br> This means the following are valid: <code>def a</code>, <code>def b()</code>, but also the contrived <code>def c()()</code> and <code>def d(x: Int)()()(y: Int)</code> etc...</p> <p>A function <code>def foo = ???</code> has zero parameter lists. A function <code>def bar() = ???</code> has precisely one parameter list, with zero parameters. <strong>Introducing additional rules that conflate the two forms would have undermined currying as a consistent language feature</strong>: <code>def a</code> would be equivalent in form to <code>def b()</code> and <code>def c()()</code> both; <code>def d(x: Int)()()(y: Int)</code> would be equivalent to <code>def e()(x: Int)(y: Int)()()</code>.</p> <p>One case where currying is irrelevant is when dealing with Java interop. Java does not support currying, so there's no problem with introducing syntactic sugar for zero-parameter methods like <code>"test".length()</code> (which directly invokes <code>java.lang.String#length()</code>) to also be invoked as <code>"test".length</code>.</p> <h1>A quick explanation of currying</h1> <p>Scala supports a language feature called 'currying', named after mathematician Haskell Curry.<br> Currying allows you to define functions with several parameter lists, e.g.:</p> <pre><code>def add(a: Int)(b: Int): Int = a + b add(2)(3) // 5 </code></pre> <p>This is useful, because you can now define <code>inc</code> in terms of a partial application of <code>add</code>:</p> <pre><code>def inc: Int =&gt; Int = add(1) inc(2) // 3 </code></pre> <p>Currying is most often seen as a way of introducing control structures via libraries, e.g.:</p> <pre><code>def repeat(n: Int)(thunk: =&gt; Any): Unit = (1 to n) foreach { _ =&gt; thunk } repeat(2) { println("Hello, world") } // Hello, world // Hello, world </code></pre> <p>As a recap, see how <code>repeat</code> opens up another opportunity to use currying:</p> <pre><code>def twice: (=&gt; Any) =&gt; Unit = repeat(2) twice { println("Hello, world") } // ... you get the picture :-) </code></pre>
 

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