why do i get `Exception in thread "main" java.lang...
# announcements
s
why do i get
Exception in thread "main" java.lang.IndexOutOfBoundsException: start 4, end 3, s.length() 3
for https://pl.kotl.in/PEocYV7Ns
Copy code
fun String.padShrinkEnd(to: Int, char: Char): String {
    val thisLength = this.length
    val build = this.removeRange(to..thisLength).toStringBuilder()
    while(build.length < thisLength) build.append(char)
    return build.toString()
}

fun main() {
    println("\"" + "abc".padShrinkEnd(2, ' ') + "\"")
}
s
Not sure about your use-case, but this solve the exception: Change
val build = this.removeRange(to..thisLength).toStringBuilder()
into
val build = this.removeRange(to until thisLength).toStringBuilder()
(replace
..
with `until`; was easy to debug, though…)
Although, the
endIndex
of
removeRange
is one past the position of the chars to be removed, according to the doc. The string’s length should be a valid value for `endIndex`….
It seems
endIndex
is inclusive for the range to remove… while the documentation says it is not inclusive….
i
endIndex
parameter is exclusive, however if you make a range from it and pass that range to
removeRange
the end index of that range is inclusive.
Note that
this.removeRange(to. thisLength)
is equivalent to
this.substring(0, to)
or just
this.take(to)
s
is
this.take
equivilant to
this.dropLast
i
take(n)
is equivalent to
dropLast(size - n)
s
ok