I'm new to Scala (Scala code runner version 2.7.7.final), and I really don't understand why it requires the caller to provide the parameter type when we are using high order functions.
In the sample below, I have one stand alone object ( Util ) that has one function. But in the Main block, the caller must pass the parameter type to the anonymous function.
Why does Scala not infer the type of the function from the Array type (i.e. String)? Is there any way to do that ?
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) =>(T,T)) {
for(i <- 0 until (arrayOne.length min arrayTwo.length)){
val (left, right) = f(arrayOne(i),arrayTwo(i))
arrayOne(i) = left
arrayTwo(i) = right
}
}
}
object Main extends Application {
val arrayOne = Array("A","B","C")
val arrayTwo = Array("D","E","F")
//If not specified the type String,the compiler throws "Missing Parameter Type" error
Util swap(arrayOne, arrayTwo,(elem1:String,elem2:String)=>(elem2,elem1))
}