dr jerry
dr jerry

Reputation: 10026

Tail on scala iterator

I want to check that every line in a file, apart from the first header line, contains the string "14022015". I wanted to do this the Scala way and I came up with something clever (I thought) usingfoldLeft:

assert(Source.fromFile(new File(s"$outputDir${File.separator}priv.txt"))
  .getLines().foldLeft(true)((bool, line) => (bool && line.contains("14022015"))))

Until I found out about the header line, which needs to be excluded from the test. tail will not work as getLines returns an Iterator and not a List. Is there something else I can do (Scala wise)?

Upvotes: 2

Views: 517

Answers (2)

Jean Logeart
Jean Logeart

Reputation: 53809

Simply:

val res: Boolean = myFile.getLines.drop(1).forall(_.contains("14022015"))

Upvotes: 6

Sergey
Sergey

Reputation: 2900

iterator.drop(1) will help you achieve exactly what you need

UPD: A side note, consider using a recursive solution instead of fold in this case - fold will always scan the entire iterator, and based on your code it looks like you may want it to short-circuit, just like standard a && b && c is not going to evaluate expressions down the list as soon as it encounters a false

Upvotes: 3

Related Questions