The approach here really depends on your requirements.
If you're after Tuple5
only when there are 5 elements defined in elem
then a simple pattern match is a way to go (and as the function returns Option
you can flatten it after map to get an expected result):
def convert(l: List[String]): Option[(String, String, String, String, String)] = l match {
case e1 :: e2 :: e3 :: e4 :: e5 :: _ => Some((e1, e2, e3, e4, e5))
case _ => None
}
Alternatively if you're after taking all the list sizes and converting them to Tuple5 with some default you can:
Use pattern matching as shown above and handle the remaining 5 cases (0,1,2,3,4 elems in the list) defaulting missing values.
Wrap your elem(n)
calls with scala.util.Try and default (i.e. Try(elem(1)).getOrElse("")
)
Add the default values to the elem
list to fill in the missing values
Example illustrating last option below:
def convert(l: List[String], default : String): (String, String, String, String, String) = {
val defaults = (1 to 5 - l.size).map(_ => default).toList
l ++ defaults match {
case e1 :: e2 :: e3 :: e4 :: e5 :: _ => (e1, e2, e3, e4, e5)
}
}