Johnny
Johnny

Reputation: 15413

Scala zipWithIndex over a sequence of Strings, do something different with last entry

I have a Seq[String] the represent a file, every String is a line in the file.

I'm iterating over the lines and parsing the record:

fileLines.zipWithIndex.foreach {
      case(fileLine, filePosition) => parseRecord(fileLine, filePosition)
}

Now, for the last record I need to do a different parsing. Let's say parseLastRecord(). What is the best Scala-way to do it?

The main reason for my question is that it would be totally fine to do the last line parsing inside parseRecord that I already use, but, I don't want to pass the filePosition+totalSize into it...

Upvotes: 1

Views: 670

Answers (2)

Wajih
Wajih

Reputation: 925

using pattern matching

val l = List(1,2,3,4)
val spe = l.length - 1
l.zipWithIndex.foreach{ case(item, pos) => {pos match { case `spe` => println(s"$item $pos special"); case _ => println(s"$item $pos");}}}

in your case

val last = fileLines.length - 1
fileLines.zipWithIndex.foreach {
      case(fileLine, filePosition) => {filePosition match { 
      case `last` => parseLastRecord(fileLine, filePosition)
      case _ => parseRecord(fileLine, filePosition);
}

Upvotes: 1

prayagupadhyay
prayagupadhyay

Reputation: 31222

While pattern matching you can check the index and call whichever function you want to call from there.

eg. if last element I'm printing something otherwise each element in following example.

List(1, 2, 3, 4).zipWithIndex.foreach{ 
    case (element, index) if index == 3 => println("last element") 
    case (element, index) => println(element)
}

output

1
2
3
last element

So, your case would be something as below,

fileLines.zipWithIndex.foreach {
  case(fileLine, filePosition) if filePosition == fileLines.length-1 => parseLastRecord(fileLine, filePosition)
  case(fileLine, filePosition) => parseRecord(fileLine, filePosition)
}

Upvotes: 2

Related Questions