Accepted answer

If you're intent on applying a function only to specific entries in a list, you could:

list.zipWithIndex.flatMap {
  case (entry, idx) if (idx == 2) =>
    entry.split(" ")
  case (entry, idx) => List(entry)

This could be generalized a little more by going along the lines of:

// Add variance, curry, etc. as needed...
def flatMapOnly[A](list: List[A], offsets: Set[Int], f: A => Seq[A]): List[A] =
  list.zipWithIndex.flatMap {
    case (entry, idx) if (offsets.contains(idx)) =>
    case (entry, _) => List(entry)

scala> flatMapOnly(List("hi", "bye", "see ya later"), Set(1, 2), { str: String => str.split(" ").toList })
res39: List[String] = List(hi, bye, see, ya, later)


 list.flatMap { 
   case x@"see ya later" => x.split(" ")
   case x => Seq(x)

Related Query

More Query from same tag