如何仅使用Scala 2.11.6 API将阵列(e1,e2)转换为(e1,e2)?

如何仅使用Scala 2.11.6 API将阵列(e1,e2)转换为(e1,e2)?,scala,Scala,鉴于: 如何将ss转换为具有数组功能的元组(hello,world)(在ss上)?我在考虑一个函数,这样上面的代码片段就会变成“hello\u world”.split(“\u”).to[Tuple2]或类似的东西 是否可以只使用Scala 2.11.6 API?我能想到的最短版本: scala> val ss = "hello_world".split("_") ss: Array[String] = Array(hello, world) 当然,对于其他非Tuple2情况,它将抛出。

鉴于:

如何将
ss
转换为具有
数组功能的元组
(hello,world)
(在
ss
上)?我在考虑一个函数,这样上面的代码片段就会变成
“hello\u world”.split(“\u”).to[Tuple2]
或类似的东西


是否可以只使用Scala 2.11.6 API?

我能想到的最短版本:

scala> val ss = "hello_world".split("_")
ss: Array[String] = Array(hello, world)
当然,对于其他非
Tuple2
情况,它将抛出。您可以使用此选项以避免出现异常:

scala> "hello_world" split("_") match { case Array(f, s) => (f, s) }
res0: (String, String) = (hello,world)
或具有以下含义:

scala> "hello_world" split("_") match { case Array(f, s) => Some(f, s); case _ => None } 
res1: Option[(String, String)] = Some((hello,world))

我对这个解决方案还是不太满意。似乎您必须写出所有可能的情况,直到
Tuple22
才能生成更通用的方法,如
到[Tuple22]
,或者可能使用宏。

不幸的是,没有函数可以转换N个元素的
数组
(当然,N我认为您做得比

def array2Tuple[T](array: Array[T]): TupleN = {
  if(array.length == 2)
    (array(0), array(1))
  else
    array(0) +: array2Tuple(array.drop(1))
}


如果不重新设计的某些特性,那么它就不是一个真正的dup,我想你为什么要这样做?如果你不知道分割会产生多少元素,你就不能说得到的元组的类型。那么你将如何处理它?如果你在寻找异构列表,请参阅Shapeless的HList将列表转换为元组的方法。可以使用这些方法从array.toList开始将数组转换为元组。
def array2Tuple[T](array: Array[T]): TupleN = {
  if(array.length == 2)
    (array(0), array(1))
  else
    array(0) +: array2Tuple(array.drop(1))
}
"size_known".split("_") match { case Array(a, b) => (a, b) }
Some("size_is_unknown".split("_")) collect { case Array(a, b) => (a, b) }