简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM