I want to get just the first line of a big string. Currently, here's how I do it:
def getFirstParagraph(txt: String) = {
val newLineIdx = txt.indexOf("\n") match {
case i: Int if i > 0 => i
case _ => txt.length
}
txt.substring(0, newLineIdx)
}
But my friend sees some downfall: if txt
is null
, there will be an exception. His suggestion involved using var
:
def getFirstParagraph(txt: String) = {
var result = txt
scala.util.control.Exception.ignoring(classOf[Exception]) {
result = result.substring(0, result.indexOf("\n"))
}
result
}
Which will handle the null
value fine. Thing is, I'm quite uncomfortable using var
. How can I handle this case without using var
(aka the Scala / functional way)?