Scala convert Int => Seq [Int] to Seq [Int => Int]

Is there a convenient way to convert a function of type Int => Seq [Int] to Seq [Int => Int] to scala? For instance:

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)
+4
source share
2 answers

This is usually not possible.

For example, you have a function x => if (x < 0) Seq(x) else Seq(x * 2, x * 3). What is the size Seqreturned by your hypothetical function?

+5
source

As @ZhekaKozlov noted, collections will be a problem because the type is the same regardless of the size of the collection.

For tuples, on the other hand, size is part of the type, so you can 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 quite a “convenient” conversion, but doable.

+2
source

Source: https://habr.com/ru/post/1677422/


All Articles