scala 如何将数组转换为元组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12585549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an Array to a Tuple?
提问by Pete Montgomery
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.
我有一个Array[Any]来自 Java JPA 的内容(在本例中为两个,但请考虑任何少量)不同类型的内容。我想将这些表示为元组。
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]) }
回答by om-nom-nom
How about this?
这个怎么样?
val pair = query.getSingleOrNone
pair collect { case Array(x: MyClass1, y: MyClass2, _*) => (x,y) }
// result would be Option[(MyClass1, MyClass2)]
回答by Asim Jalis
Use map { case Array(f1,f2) => (f1,f2) }.
使用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)}
回答by Jianfeng Tian
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))

