If you don't care about validation, you could do this:
fun toRange(str: String): IntRange = str
.split(";")
.let { (a, b) -> a.toInt()..b.toInt() }
fun main() {
println(toRange("10;15;1"))
}
Output:
10..15
If you want to be more paranoid:
fun toRange(str: String): IntRange {
val split = str.split(";")
require(split.size >= 2) { "str must contain two integers separated by ;" }
val (a, b) = split
return try {
a.toInt()..b.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("str values '$a' and/or '$b' are not integers", e)
}
}
fun main() {
try { println(toRange("oops")) } catch (e: IllegalArgumentException) { println(e.message) }
try { println(toRange("foo;bar;baz")) } catch (e: IllegalArgumentException) { println(e.message) }
println(toRange("10;15;1"))
}
Output:
str must contain two integers separated by ;
str values 'foo' and/or 'bar' are not integers
10..15
Intmight be simpler thanBigDecimal. This looks too specific to be worth splitting out to a separate function, unless you can make it more general somehow.map(String::toBigDecimal)so the code is more self-documenting without losing its conciseness.