Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the FunctionN trait that represents a function taking a by-name parameter?
    text
    copied!<p>A function in Scala is an object that implements one of the <code>FunctionN</code> traits. For example:</p> <pre><code>scala&gt; def f(x: Int) = x * x f: (x: Int)Int scala&gt; val ff = f _ ff: Int =&gt; Int = &lt;function1&gt; scala&gt; val fff: Function1[Int, Int] = f _ fff: Int =&gt; Int = &lt;function1&gt; </code></pre> <p>So far, so good. But what if we have a function that takes a by-name parameter? It certainly does still implement one of the <code>FunctionN</code> traits:</p> <pre><code>scala&gt; def g(x: =&gt; Int) = x * x g: (x: =&gt; Int)Int scala&gt; val gg = g _ gg: =&gt; Int =&gt; Int = &lt;function1&gt; scala&gt; gg.isInstanceOf[Function1[_, _]] res0: Boolean = true </code></pre> <p>But what type is it, exactly? It's not <code>Function1[Int, Int]</code>:</p> <pre><code>scala&gt; val ggg: Function1[Int, Int] = g _ &lt;console&gt;:8: error: type mismatch; found : =&gt; Int =&gt; Int required: Int =&gt; Int val ggg: Function1[Int, Int] = g _ ^ </code></pre> <p>Nor is it <code>Function1[Function0[Int], Int]</code>:</p> <pre><code>scala&gt; val ggg: Function1[Function0[Int], Int] = g _ &lt;console&gt;:8: error: type mismatch; found : =&gt; Int =&gt; Int required: () =&gt; Int =&gt; Int val ggg: Function1[Function0[Int], Int] = g _ ^ </code></pre> <p>And <code>Function1[=&gt; Int, Int]</code> fails to compile:</p> <pre><code>scala&gt; val ggg: Function1[=&gt; Int, Int] = g _ &lt;console&gt;:1: error: identifier expected but '=&gt;' found. val ggg: Function1[=&gt; Int, Int] = g _ ^ </code></pre> <p>So what is it?</p>
 

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