Reputation: 10324
I have to define a second order function that takes as a parameter a function.
In my application, the input function may have any input type, but the output type has to be a specified one (suppose Int, it does not matter).
I define the second order function has:
def sof(f : (Any => Int) ) = {...}
Now, if I have a function f : Int => Int
, and I call:
sof(f)
I get:
found : Int => Int
required: Any => Int
I guess I am misunderstanding the meaning of the Any type.
How can I make it work?
Upvotes: 3
Views: 145
Reputation: 1905
You shouldn't use Any
there, but a type parameter such as:
def sof[A](f: A => Int) = {...}
However I don't think you can do much with that method. Probably you would want something like this:
def sof[A](a: A)(f: A => Int) = f(a)
// usage example
val x = sof("hello")(_.size * 2) // the result is 10
// you can also partially apply it to obtain other functions
val sizeDoubler: String => Int = sof(_)(_.size * 2)
val helloDoubleSize = sizeDoubler("hello") // the result is 10
This way you can pass any type to sof
plus you'll have the compiler by your side to signal any strange behaviour. Using Any
you lose this ability.
Final Note: In case the syntax I used to pass two parameters (the A
value and the A => Int
function) to a method looks strange to you that's called currying. If you Google it you'll find many good articles about it.
Upvotes: 2
Reputation: 11882
The parameters of functions in Scala are contravariant. That means that Int => Int
is not a subtype of Any => Int
, but vice-versa. Imagine the following: You pass a String to the Any => Int
function (that is actually implemented by a Int => Int
function). How would the Int => Int
handle the String argument?
Upvotes: 4