Note that there are some explanatory texts on larger screens.

plurals
  1. POTwo ways of defining functions in Scala. What is the difference?
    primarykey
    data
    text
    <p>Here is a little Scala session that defines and tries out some functions:</p> <pre><code>scala&gt; def test1(str: String) = str + str; test1: (str: String)java.lang.String scala&gt; test1("ab") res0: java.lang.String = abab </code></pre> <p>works nicely.</p> <pre><code>scala&gt; val test2 = test1 &lt;console&gt;:6: error: missing arguments for method test1 in object $iw; follow this method with `_' if you want to treat it as a partially applied function val test2 = test1 ^ </code></pre> <p>oops. </p> <pre><code>scala&gt; val test2 = test1 _ test2: (String) =&gt; java.lang.String = &lt;function1&gt; scala&gt; test2("ab") res1: java.lang.String = abab </code></pre> <p>works well!</p> <p>Now, I've seen the <code>_</code> syntax when folding (<code>_ + _</code>, etc). So as I understand it <code>_</code> basically means "an argument". So <code>test1 _</code> basically means a function with an argument, which is given to <code>test1</code>". But why isn't that <em>exactly</em> the same as just <code>test1</code>? Why is there a difference if I append a <code>_</code>?</p> <p>So I kept exploring...</p> <pre><code>scala&gt; val test3 = (str: String) =&gt; str + str test3: (String) =&gt; java.lang.String = &lt;function1&gt; scala&gt; test3("ab") res2: java.lang.String = abab scala&gt; val test4 = test3 test4: (String) =&gt; java.lang.String = &lt;function1&gt; </code></pre> <p>Here it works without <code>_</code>! What's the difference between a <code>def</code>ed function, and a <code>val</code>ed function?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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