0

I'm having a tuple of 3 elements and trying to zip with an Array of size=3 using the below approach

val tup3= (10:BigInt,9:BigInt,3:BigInt)
val arr3:Array[String] = Array("cnt", "mxid2","nullid3")
val map_result = tup3.productIterator.toArray.zip(arr3).map( x => (x._2,x._1)).toMap

when I try the other way around to avoid the swapping of elements, I'm getting error

arr3.zip(tup3.productIterator.toArray)

<console>:30: error: polymorphic expression cannot be instantiated to expected type;
 found   : [B >: Any]Array[B]
 required: scala.collection.GenIterable[?]
       arr3.zip(tup3.productIterator.toArray)
                                 ^

how to fix this error?.

stack0114106
  • 8,534
  • 3
  • 13
  • 38
  • 1
    Just removing `toArray` fixes this: `arr3.zip(tup3.productIterator)` – jrook Feb 24 '20 at 19:33
  • Also relevant: https://stackoverflow.com/q/5544536/2928853 explains why things like this happen. In any case, this will be fixed in Dotty. – jrook Feb 25 '20 at 19:12
  • @jrook.. so it seems to be a bug which will be fixed in Dotty.. btw I'm using 2.11.8 in spark 2.3 – stack0114106 Feb 25 '20 at 20:00
  • Another trick would be to make the type parameter explicit: `arr3.zip(tup3.productIterator.toArray[Any])` if the other one doesn't work. – jrook Feb 25 '20 at 21:18

1 Answers1

2

Do you need a generic solution for any array and tuple size?

Because if not, I would just be lazy and do this:

(array, tuple) match {
  case ((key1, key2, key3), (value1, value2, value3)) =>
    val map = Map(
      key1 -> value1,
      key2 -> value2,
      key3 -> value3
    )

  case _ =>
    Map.empty[String, Any]
}
  • 1
    You need something like shapeless to do a generic solution: https://scalafiddle.io/sf/7K8YObw/4 – Ethan Feb 24 '20 at 23:31
  • 1
    It seems like overkill in this case, since your answer exactly resolves the question, but might be worth mentioning the more generic case. That only does one direction, but easy enough to duplicate for the other. – Ethan Feb 24 '20 at 23:32
  • @Ethan pretty cool, thanks for the addition, feel free to provide your own answer or edit mine. - BTW, personal opinion, if I would need a more generic solution I would probably just write a source generator, I am really scared of **Shapeless** (lmao). – Luis Miguel Mejía Suárez Feb 24 '20 at 23:34