Equivalent of LPAD Function in Scala

Please does anybody know a standard function in scala that can be used for LPAD that we have in SQL? See sample use below

select LPAD(‘123’,5,‘0’) Test_Lpad

What does it do?

This is supposed to pad the string 123 with 0s on the left to make it have a length of 5.
That is 123 will become 00123.
I hope this clarifies it?

If you happen to be using Spark, How to add leading zero padding with the specified number of digits in scala spark? - Stack Overflow

Otherwise, scala - How to convert an Int to a String of a given length with leading zeros to align? - Stack Overflow

Thanks @SethTisue

For the generic case (string input to start with, arbitrary padding char and length), no standard functionality I’m aware of, but perhaps something along these lines:

def lpad(c: Char, n: Int)(s: String): String =
  (c.toString * (n - s.length)) + s
@ lpad('0', 5)("123") 
res1: String = "00123"

@ lpad('0', 2)("123") 
res2: String = "123"

@ lpad('-', 7)("123") 
res3: String = "----123"

@ lpad('-', -2)("123") 
res4: String = "123"

As from the linked solutions, padTo springs to mind.

scala> "123".view.reverse.padTo(5, '0').mkString.reverse
val res0: String = 00123

You could also use something like this:

scala> def padTo5(s: String) = "%05d".format(s.toInt)
def padTo5(s: String): String
scala> padTo5("123")
val res2: String = 00123

For more generality, the desired length could also be a parameter.

I would always use f-interpolator for type safety.

For the dynamic format case, I lodged

There is Aptus too: https://github.com/aptusproject/aptus-core#string-operations

I saw 1.str .padLeft (3, '0').p // "001" there.