Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Array to a Tuple?

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]) } 
like image 374
Pete Montgomery Avatar asked Sep 25 '12 14:09

Pete Montgomery


People also ask

How do you convert a tuple to an array in Python?

To convert a tuple of lists into an array, use the np. asarray() function and then flatten the array using the flatten() method to convert it into a one-dimensional array.

Can we convert list to tuple in Python?

You can convert a list into a tuple simply by passing to the tuple function.

How do you convert a list to a list of tuples?

To convert a list of lists to a list of tuples: Pass the tuple() class and the list of lists to the map() function. The map() function will pass each nested list to the tuple() class. The new list will only contain tuple objects.


1 Answers

How about this?

val pair = query.getSingleOrNone pair collect { case Array(x: MyClass1, y: MyClass2, _*) => (x,y) } // result would be Option[(MyClass1, MyClass2)] 
like image 79
om-nom-nom Avatar answered Oct 08 '22 22:10

om-nom-nom