1

I'm pretty new to scala programming and would like to write a function returning a tuple instance by the arguments passed in. Here is what I mean:

def toTuple(strings : String*) = {
   //some code to create a tuple, if possible
   //the tuple should be consistent with the order the arguments were passed in
}

Is it possible to do so in scala?

stella
  • 2,546
  • 2
  • 18
  • 33
  • See the linked question, but to better help, what to you want to achieve in the end / what is your idea behind it? – Elmar Weber Jul 18 '15 at 11:37
  • @ElmarWeber There's no idea behind it, I'm simply learning scala and trying diffenret examples. – stella Jul 18 '15 at 11:46
  • For historical reasons it's hard to abstract over scala tuples (this will be fixed in an upcoming version but that's probably a few years in the future). In general if you want to work generically it's better to use shapeless `HList`s. – lmm Jul 20 '15 at 09:05

1 Answers1

1

The problem is with returning type of this function. What should it be? Any? But that doesn't sound like a good static typing. I suggest you to use something like that:

def toTuple(strings : String*): (String, String) = strings.toList match{
  case Nil => ("", "")
  case a :: Nil => (a, "")
  case a :: b :: xs => (a, b)
}

Usage:

scala> toTuple(List("a"): _*)
res2: (String, String) = (a,"")

scala> toTuple(List("a", "b"): _*)
res3: (String, String) = (a,b)
Nikita
  • 4,435
  • 3
  • 24
  • 44