0

This is my very first try for scala in play framework. What I really want to achieve is to take every first word from sentences in a paragraph.

This is the code that throws an error

Text is mutable.Seq[String]

someText.flatMap(_ split "[.?!]")
  .map(_ split "\\s+" filter !_.equals("") head)
  .toList

But the problem is on 2nd line. It throws an error saying that:

[NoSuchElementException: next on empty iterator]

In my humble opinion, sentence separated by whitespace will not be empty as long as the someText is a real paragraph with a lot of sentences.

Could somebody clarify, how this could happened and how to fix it?

cchantep
  • 9,118
  • 3
  • 30
  • 41
muhrifqii
  • 19
  • 2
  • 9
  • You use `.head` which is unsafe. Better to use `.headOption`. – cchantep Jun 04 '16 at 16:50
  • @cchantep Thanks. `headOption` fix this. – muhrifqii Jun 04 '16 at 17:05
  • Using `headOption` will fix the problem, but will not tell you what it was. It also changes the type of the result. Think about what happens if one of the input strings is empty, or only contains whitespace. You should learn to use debugging (or print out statements) to answer questions like this yourself. – Dima Jun 04 '16 at 17:22

2 Answers2

1
  1. First, I think that your regex isn't ok, see here. It will match any character with dot .. If you want to treat it at as a dot character, you need to escape it like \\..
  2. Is your someText an Option[String]? I don't understand why you flatMap it.
  3. When you call head on an empty collection you'll get an exception, be aware of that.
  4. If your question still holds, I would do something like this:

val someTex = "" val lines = someText.split("\\.").map(_.trim).toList val firstWords = lines.flatMap(_.split("\\s+").headOption)

insan-e
  • 3,883
  • 3
  • 18
  • 43
0

You use the .head operation, which is unsafe (exception in case the collection is empty).

You'd better use .headOption:

someText.flatMap(_ split "[.?!]")
  .flatMap(_ split "\\s+" filter !_.equals("") headOption toList)
  .toList
cchantep
  • 9,118
  • 3
  • 30
  • 41
  • This explain the `NoSuchElementException` of the question, so @Dima can you explain constructively why you don't consider it an answer? – cchantep Jun 04 '16 at 17:56