woooking
woooking

Reputation: 43

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

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)

Upvotes: 4

Views: 830

Answers (2)

jwvh
jwvh

Reputation: 51271

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.

Upvotes: 2

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

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?

Upvotes: 5

Related Questions