将可变长度的数组转换为scala中的元组 [英] converting array of variable length to tuple in scala

查看:39
本文介绍了将可变长度的数组转换为scala中的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个元组,但是这个元组的大小需要在运行时根据变量值改变.我真的不能在 Scala 中做到这一点.所以我创建了一个数组:

I need to create a tuple but this tuple's size need to change at run time based on variable value. I can't really do that in scala. So i created an array:

val temp:Array[String] = new Array[String](x)

如何将数组转换为元组.这可能吗?我是 Scala 新手.

How do I convert the array to tuple. is this possible? i'm a scala newbie.

推荐答案

为了创建元组,您必须知道预期的大小.假设你有,那么你可以做这样的事情:

In order to create a tuple, you have to know the intended size. Assuming you have that, then you can do something like this:

val temp = Array("1", "2")
val tup = temp match { case Array(a,b) => (a,b) }
// tup: (String, String) = (1,2)

def expectsTuple(x: (String,String)) = x._1 + x._2
expectsTuple(tup)

这允许您将元组传递给任何需要它的函数.

And that allows you to pass the tuple to whatever function expects it.

如果你想变得更高级,你可以定义 .toTuple 方法:

If you want to get fancier, you can define .toTuple methods:

implicit class Enriched_toTuple_Array[A](val seq: Array[A]) extends AnyVal {
  def toTuple2 = seq match { case Array(a, b) => (a, b); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple2: Array(${x.mkString(", ")})") }
  def toTuple3 = seq match { case Array(a, b, c) => (a, b, c); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple3: Array(${x.mkString(", ")})") }
  def toTuple4 = seq match { case Array(a, b, c, d) => (a, b, c, d); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple4: Array(${x.mkString(", ")})") }
  def toTuple5 = seq match { case Array(a, b, c, d, e) => (a, b, c, d, e); case x => throw new AssertionError(s"Cannot convert array of length ${seq.size} into Tuple5: Array(${x.mkString(", ")})") }
}

这让您可以:

val tup = temp.toTuple2
// tup: (String, String) = (1,2)

这篇关于将可变长度的数组转换为scala中的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆