Scala weird implicit boxing conversion error

Can someone tell me why the following is not working?

object TestObject { def map(f: (Double, Double) => Double, x2: Array[Double]) = { val y = x2.zip( x2 ) val z = y.map(f) z } } 

Produces this error:

 type mismatch; found : (Double, Double) => Double required: ((Double, Double)) => ? 
+2
source share
3 answers

In this snippet, f is a function that takes two Double parameters and returns Double . You are trying to call f by passing one argument of type Tuple2[Double,Double] . You can fix this by changing the type f first:

 object TestObject { def map(f: ((Double, Double)) => Double, x2: Array[Double]) = { val y = x2.zip( x2 ) val z = y.map(f) z } } 

You can also declare it as f: Tuple2[Double, Double] => Double more understandable (this is completely equivalent).

Conversely, you can change your call as follows:

 object TestObject { def map(f: (Double, Double) => Double, x2: Array[Double]) = { val y = x2.zip( x2 ) val z = y.map(f.tupled) z } } 

tupled will automatically convert your function (Double, Double) => Double to the function Tuple2[Double, Double] => Double . Keep in mind that the conversion will be performed each time TestObject.map called TestObject.map

+4
source

There is a subtle difference between

 f: (Double, Double) => Double // two Double arguments -> Double 

and

 f: ((Double, Double)) => Double // one Tuple2[Double, Double] argument -> Double 

y is Array[(Double, Double)] , so it expects a method that takes a tuple and returns something, but the first f defined above does not match this.

You can do y.map(f.tupled) to go from the first to the second, or change the signature of f .

+2
source

I think your problem is that f expects two Double arguments, but you are trying to pass one tuple to it: f((1, 2)) is different from f(1, 2) .

Change type f to ((Double, Double) => Double) and it should work.

+1
source

Source: https://habr.com/ru/post/1487262/


All Articles