Scala higher order overloaded functions cause an error like

I have an overloaded method that is defined as follows:

def g(f: () β‡’ Double): Object = null def g(f: Double β‡’ Double): Object = null def g(f: (Double, Double) β‡’ Double): Object = null def h(f: (Double, Double) β‡’ Double): Object = null 

While h(math.max _) works as expected, calling g(math.max _) gives me the error "Overloaded method ... cannot be applied to ((Int, Int) => Int)". It seems that the compiler chose the Int math.max version instead of Double.

How can I call my overloaded method g using math.max as a parameter? This would be an added bonus if I could just call g(math.max) without underlining.

+4
source share
2 answers

You have come across the heuristics used by the compiler to avoid exponentially complex type searches. When a method is overloaded, it tries to disambiguate depending on the type of argument. Unfortunately, the argument is also overloaded. Instead of trying out the possibilities, it just captures the first that comes to mind and it doesn't work.

You can trick him into looking for more by setting the correct path:

 g(math.max(_,_)) 

It’s now justified to the compiler that he is looking for Function2 and that - although all versions of max must be Function2 ! - enough to get the compiler to do a matching search (and it matches Double with Double ).

+3
source

A few minutes after posting this, I discovered this solution:

 g(math.max: ((Double, Double) => Double)) 

I'm still wondering why Scala has a problem in the first case.

+1
source

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


All Articles