28

I have an Array[Any] from Java JPA containing (two in this case, but consider any a small number of) differently-typed things. I would like to represent these as tuples instead.

I have some quick and dirty conversion code, and wondered how it could be improved and perhaps made more generic.

val pair = query.getSingleOrNone // returns Option[Any] (actually a Java array)
pair collect { case array: Array[Any] =>
  (array(0).asInstanceOf[MyClass1], array(1).asInstanceOf[MyClass2]) }
Nikita
  • 333
  • 3
  • 8
Pete Montgomery
  • 4,060
  • 3
  • 30
  • 40
  • Does this answer your question? [Extract values from Array into Tuple](https://stackoverflow.com/questions/16765473/extract-values-from-array-into-tuple) – Flow Jun 05 '21 at 09:10

4 Answers4

38

How about this?

val pair = query.getSingleOrNone
pair collect { case Array(x: MyClass1, y: MyClass2, _*) => (x,y) }
// result would be Option[(MyClass1, MyClass2)]
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
24

Use map { case Array(f1,f2) => (f1,f2) }.

Here is an example:

Array( "CA:California", "WA:Washington", "OR:Oregon").
  map(s => s.split(":")).
  map { case Array(f1,f2) => (f1,f2)}
Asim Jalis
  • 884
  • 9
  • 8
13

My solution is as below:

val loginValues = line.split(",")  // return an Array

val (ip, date, action, username) = (loginValues(0), loginValues(1).toLong, loginValues(2), loginValues(3))
Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
Jianfeng Tian
  • 155
  • 1
  • 2
4

You can use Tuple.fromArray. Works for Scala 3.0.2, haven't checked earlier versions.

scala> val a = Array("a", "b")
val a: Array[String] = Array(a, b)

scala> Tuple.fromArray(a)                                                        
val res1: Tuple = (a,b)

ppopoff
  • 658
  • 7
  • 17