Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala, currying and overloading

Say you have the following:

foo(x: String)(y: Int): Int
foo(x: String)(y: Double): Int

Scala does not allow such expression. As far as I can see, the reason for this is that foo("asdf") does not have a well defined type (it's either Int => Int or Double => Int).

Is there a reason why such "polytyped" functions should not be allowed?

like image 889
Henry Henrinson Avatar asked Aug 24 '11 16:08

Henry Henrinson


People also ask

What is Scala currying?

Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. It is applied widely in multiple functional languages. Syntax. def function name(argument1, argument2) = operation.

What is the advantage of currying in Scala?

Advantages of Currying Function in Scala One benefit is that Scala currying makes creating anonymous functions easier. Scala Currying also makes it easier to pass around a function as a first-class object. You can keep applying parameters when you find them.


1 Answers

Overloading resolution in Scala takes only the first parameter list into account. That's why alternatives must differ already in this list. There's a good reason for this: We can then use the resolved function's type to infer the type of subsequent arguments. This enables idioms like:

xs.corresponds(ys) { (x, y) => x < y }

Note that here we need to know the type of corresponds in order to infer the types of x and y. It would be a shame to have this break down when corresponds is overloaded.

like image 186
Martin Odersky Avatar answered Oct 21 '22 15:10

Martin Odersky