debugModerate
A safer way to cut a string
Viewed 0 times
safercutwaystring
Problem
I want to get just the first line of a big string. Currently, here's how I do it:
But my friend sees some downfall: if
Which will handle the
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)?Solution
Here's my take on it:
As to the
Handling
def getFirstParagraph(txt: String): String = txt.lines.nextAs to the
null objection: in idiomatic Scala, you don't use null. If there's some API which might return you a null string, then, at that point, you turn it into an Option, and handle the Option elsewhere as needed.Handling
null (or even Option) at the getFirstParagraph method is misplaced.Code Snippets
def getFirstParagraph(txt: String): String = txt.lines.nextContext
StackExchange Code Review Q#14596, answer score: 12
Revisions (0)
No revisions yet.