1

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)

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

3
  • Is the size the only thing that will vary at runtime? How about the type of the items in your tuple? Will it always be String as your example suggest? Commented Jul 10, 2014 at 17:44
  • 2
    A tuple is by definition a heterogeneous element fixed-arity thing. If you need a dynamic number of strings, you can use any type of collection. Why do you want to convert that into a "tuple"? Commented Jul 10, 2014 at 17:45
  • I need a tuple because I need to feed a tuple to another class's method, which I don't have control of. Yes, the tuple is of type String Commented Jul 10, 2014 at 17:54

2 Answers 2

4

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.


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(", ")})") }
}

This lets you do:

val tup = temp.toTuple2
// tup: (String, String) = (1,2)
Sign up to request clarification or add additional context in comments.

Comments

0

Ran into a similar problem. I hope this helps.

(0 :: 10 :: 50 :: Nil).sliding(2, 1).map( l => (l(0), l(1)))

Results:

List[(Int, Int)] = List((0,10), (10,50))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.