Skip to content

Instantly share code, notes, and snippets.

@NikitaMelnikov
Created May 5, 2016 10:32
Show Gist options
  • Save NikitaMelnikov/44739b8f787d968296ad63ed8e2f52a8 to your computer and use it in GitHub Desktop.
Save NikitaMelnikov/44739b8f787d968296ad63ed8e2f52a8 to your computer and use it in GitHub Desktop.
Safe substring with Scala
implicit class StringExtension(s: String) {
implicit def safeSubstring(start: Int, end: Int = 0): String = {
if (start < 0) {
var realStart = s.length - Math.abs(start)
var realEnd = end match {
case 0 => s.length
case e if e < 0 || e + realStart > s.length => s.length
case _ => realStart + end
}
s.substring(realStart, realEnd)
} else {
s.substring(start, if (end > s.length) {s.length} else {end})
}
}
}
println("Hello World".safeSubstring(0, 5)) // Hello
println("Hello World".safeSubstring(-5, 5)) // World
println("Hello World".safeSubstring(-5, 1000)) // World
println("Hello World".safeSubstring(-5)) // World
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment