beefyhalo
beefyhalo

Reputation: 1841

Idiomatic Function Transformation of A => (B, C) to A => (C, B)

Is there an idiomatic way of transforming a function

val x: A => (B, C) = ...

to

val y: A => (C, B) = ...

Upvotes: 3

Views: 143

Answers (1)

Peter Neyens
Peter Neyens

Reputation: 9820

  • You can change a (B, C) to a (C, B) using Tuple2.swap.
  • Turning a A => (B, C) into a A => (C, B) can then be done using .andThen(_.swap).

For example :

scala> val a = (i: Int) => (s"$i", i.toDouble)
a: Int => (String, Double) = <function1>

scala> val b = a.andThen(_.swap)
b: Int => (Double, String) = <function1>

scala> b(5)
res1: (Double, String) = (5.0,5)

Upvotes: 15

Related Questions