[SalesForce] String.leftPad(Integer, String) method not working as expected

So I have a bit of code that is supposed to pad strings of with zeros if they have a length of less than six in order to get them up to six. To accomplish this I've used the String.leftPad(Integer, String) method.

String key = '1234';
key = key.leftPad(6 - key.length(), '0');

This is supposed to output the string 001234 however it's no longer working. This is code that has been in production for nearly six months. Looking at the documentation this method is not shown, though it compiles just fine and I would swear that it worked when I initially developed it.

Is this a bug? Was functionality removed? Did I somehow tap into something that I shouldn't have?

Best Answer

Looks like an undocumented feature to me.

Worked up a quick test in one of my dev environments, and I got it to both compile and work.

Strangely enough, it even works when I turn down the Salesforce API Version below the point where the leftPad() method was introduced (v26.0, page 181 of the release notes)

From my brief testing, this undocumented method behaves the same as with the documented leftPad(Integer) method. The integer passed should be the length of the output string. If the passed integer is less than/equal to the input string, then nothing is done (simply returns the input string).

This has been the documented behavior (ie. the passed integer being the target size of the resulting string instead of the number of characters to pad) for as long back in the docs as I can see (back to API v 29.0)

In your example, you end up calling key.leftPad(2, '0'), and as your key's length is 4, nothing happens.

If you change your call to key.leftPad(6, '0'), it should work as intended.