Reputation: 109
I am fairly new to Scala and I have to use a function which takes as argument of type Seq[Seq[Double]]
. However, my data has the type Array[(Double,Double)]
.
I tried using .toSeq
to convert the data, but that doesn't work.
Any fixes in this regard would be highly appreciated. Thanks!
Upvotes: 0
Views: 363
Reputation: 128011
val input: Array[(Double, Double)] = ...
val output: Seq[Seq[Double]] = input.map { case (x, y) => Seq(x, y) }
Unfortunately, there is no generic way to type-safely convert a tuple to a list in the standard library. shapeless, however, does provide this functionality:
import shapeless.syntax.std.tuple._
val input: Array[(Double, Double)] = ...
val output: Seq[Seq[Double]] = input.map(_.toList)
Shapeless is smart enough to compute a lowest upper bound in case your tuple contains components of different types:
val input: Array[(Double, Int)] = ...
// AnyVal is the closest type which both Double and Int are subtypes of
val output: Seq[Seq[AnyVal]] = input.map(_.toList)
Finally, there is a non-type-safe way to do this using only the standard library tools. You can rely on the fact that all tuples in Scala implement the Product trait and therefore are iterable as collections of Any
:
val input: Array[(Double, Double)] = ...
val output: Seq[Seq[Double]] = input.map(_.productIterator.toSeq.asInstanceOf[Seq[Double]])
This is safe as long as you're careful, but it does require an explicit cast and it is more verbose.
If you have fixed-length tuples of relatively small size, then I'd say it is better to use the partial function-based approach. Otherwise, it is up to you, but I'd use shapeless because it is type safe, and I also use shapeless in many of my projects for other things as well, so it is kind of free for me :)
Upvotes: 4