Created
May 5, 2016 10:32
-
-
Save NikitaMelnikov/44739b8f787d968296ad63ed8e2f52a8 to your computer and use it in GitHub Desktop.
Safe substring with Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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