Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It doesn't infer the type of <code>T</code> because the only thing it has to go by at this point would be <code>arrayOne</code> and <code>arrayTwo</code>. However, Scala does not use the type of one parameter to infer the type of another, probably because it would cause problems with method overloading. However, it works if you curry it:</p> <pre><code>Object Util { // Just for fun! Suppose that the arrayOne and arrayTwo are all the same length. // will swap the elements from arrayOne to ArrayTwo. def swap[T](arrayOne:Array[T], arrayTwo:Array[T])(f:(T,T) =&gt;(T,T)) : Unit = { var i = 0 var tuple :Tuple2[T,T] = null while(i &lt; arrayOne.length &amp;&amp; i &lt; arrayTwo.length){ tuple =f(arrayOne(i),arrayTwo(i)) arrayOne(i) = tuple._1 arrayTwo(i) = tuple._2 i+=1 } } } object Main extends Application { // val works fine below -- the object is mutable val arrayOne = Array("A","B","C") val arrayTwo = Array("D","E","F") (Util swap(arrayOne, arrayTwo))((elem1,elem2)=&gt;(elem2,elem1)) // The weird parenthesis is caused by mixing operator notation and currying // One could also write it like this: // Util.swap(arrayOne, arrayTwo)((elem1,elem2)=&gt;(elem2,elem1)) } </code></pre> <p>The reason why it works fine if you curry it is that a curried method is actually a method receiving the first parameter list and returning a function that requires the other (or others) parameter list. Because of that, overloading can be decided in the first parameter list, so the second parameter list can take advantage of inferred types.</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