2

I tried using padEnd() twice on a String. The first time the padEnd() extension function works as expected, but the second time, it does not add the any characters I tried.

My code:

var s = "Hi -> "
s = s.padEnd(10, 'O')
s = s.padEnd(5, ' ')
println(s)

My output:

Hi -> OOOO

I am using kotlin version 1.2.50. I also tried Jetbrains' online compiler to prevent the bug being only on my computer, with the same result. I also tried using a different version of kotlin (1.0.7 and 1.1.60), with still the same feature/bug.

I also tried using the padStart(), with the same behaviour, just adding it in front of the String.

Mixing the two extension functions also did not work as expected: Using padStart() and immediately after that padEnd()

Is this an expected feature? If so why is it expected? Or is it just a bug?

2 Answers 2

3

padEnd doesn't add the given character to your String the given number of times - the first parameter is the target length that it will pad up to. From the docs:

Returns a char sequence of length at least length consisting of this char sequence appended with padChar as many times as are necessary to reach that length.

So in your second call, you're trying to pad "Hi -> 0000" until it's at least 5 characters long - which it already is, so no spaces are added at its end.

3
  • I tried changing the example as you suggested s = s.padEnd(20, ' ') being the last line of my code, with the same result. Nothing changed Commented Jul 3, 2018 at 2:51
  • 2
    Ok sorry, I forgot that I added the spaces, and did not manage to see them :D Commented Jul 3, 2018 at 2:53
  • 1
    A fun thing to debug by just looking at the output for sure :)
    – zsmb13
    Commented Jul 3, 2018 at 2:55
0

You could also do something like:

val outerChar =  "*"
val x = outerChar.padEnd(10)
        .plus("hello")
        .plus(outerChar.padStart(10))
println(x)

// Prints:
// *         hello         *

This will put 10 spaces between the * and hello on each side. Also try swapping the calls to padEnd and padStart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.