It depends on what you mean by flip.
Flip as in "change the value of two variables"
If you mean that
var a = 1
var b = 2
flip(a, b)
should result in a
being 2 and b
being 1, as one could do with references in C++, then this is not possible in Scala. Here is an explanation.
Flip as in "return a tuple of the arguments in reversed order"
This is already answered perfectly in Pedro's post.
If this is what you want, you probably should use generics though, as mentioned by Luis in the comments.
Flip as in "turn a functions arguments around"
Given the signature you tried to write, your attempt looks to me as if you were trying to write a function which gets a function f
and returns a new function, same as f
, but with reversed argument order.
You can write such a function like this:
def flipAny(f: (Any, Any) => Any): (Any, Any) => Any =
(a, b) => f(b, a)
and then call it on a function like this:
def stringify(a: Any, b: Any): String =
s"a: ${a.toString}, b: ${b.toString}"
println(stringify(1,2)) // prints a: 1, b: 2
println(flipAny(stringify)(1,2)) // prints a: 2, b: 1
We can do better however, because using Any
everywhere removes valuable type information.
What happens if we try to use the string result of stringify
?
println(stringify(1,2).length) // prints 10
//println(flipAny(stringify)(1,2).length) // doesn't compile
The second line doesn't compile because flipAny
returns a function returning Any
, not String
.
Here is another definition using generics:
def flip[A, B, C](f: (A, B) => C): (B, A) => C =
(a, b) => f(b, a)
This is much better. We are getting a function from A
and B
to C
and returning a function from B
and A
to C
. This retains the type information:
println(stringify(1,2)) // prints a: 1, b: 2
println(flip(stringify)(1,2)) // prints a: 2, b: 1
println(stringify(1,2).length) // prints 10
println(flip(stringify)(1,2).length) // prints 10