Search code examples
scalascalding

convert list of elements to tuple5, prevent index out of bounds


I'm trying to create a tuple from a scala list:

.map('path -> ('uri1, 'uri2, 'uri3, 'uri4, 'uri5)) {elems:List[String] =>

  (elems(0), elems(1), elems(2), elems(3), elems(4)) //ouf of bounds!
}

But the elems may have between 1 and 5 elements, so obviously I will hit an index out of bounds exception.

What's the scala/scalding way of doing this? I'm guessing that the proper way is to iterate a range from 1 to 5 and generate the tuple from there.

I'd like to return null (for compatibility reasons) when the elements do not exist.


Solution

  • You can pad the list with nulls as necessary:

    .map('path -> ('uri1, 'uri2, 'uri3, 'uri4, 'uri5)) {elems:List[String] =>
      val padded= elems ++ List.fill(5)(null)
      (padded(0), padded(1), padded(2), padded(3), padded(4))  //No ouf of bounds!
    }