Is there a convenient way to convert a function with type Int => Seq[Int] to Seq[Int => Int] in scala? For example:
val f = (x: Int) => Seq(x * 2, x * 3)
I want to convert it to
val f = Seq((x: Int) => x * 2, (x: Int) => x * 3)
Generally, it is impossible.
For example, you have a function x => if (x < 0) Seq(x) else Seq(x * 2, x * 3)
. What is the size of the Seq
that your hypothetical function will return?
As @ZhekaKozlov has pointed out, collections are going to be a problem because the type is the same no matter the size of the collection.
For tuples, on the other hand, the size is part of the type so you could do something like this.
val f1 = (x: Int) => (x * 2, x * 3) //f1: Int => (Int, Int)
val f2 = ((x:Int) => f1(x)._1, (y:Int) => f1(y)._2) //f2: (Int => Int, Int => Int)
Not exactly a "convenient" conversion, but doable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With