HiveBrain v1.2.0
Get Started
← Back to all entries
debugModerate

A safer way to cut a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
safercutwaystring

Problem

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)?

Solution

Here's my take on it:

def getFirstParagraph(txt: String): String = txt.lines.next


As 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.next

Context

StackExchange Code Review Q#14596, answer score: 12

Revisions (0)

No revisions yet.