How to convert an Array to a Tuple?

落花浮王杯 提交于 2019-12-17 11:27:12

问题


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]) }

回答1:


How about this?

val pair = query.getSingleOrNone
pair collect { case Array(x: MyClass1, y: MyClass2, _*) => (x,y) }
// result would be Option[(MyClass1, MyClass2)]



回答2:


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)}



回答3:


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))


来源:https://stackoverflow.com/questions/12585549/how-to-convert-an-array-to-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!