0

What is the Java equivalent of the following Scala code snippet?

val codeLength = 8
val value: Long = 12345678
("0" * codeLength + value.toString).takeRight(codeLength)

It is the third line I am particularly interested in knowing what the Java 8 equivalent is.

2
  • 3
    If you explain what this code does, you'll be able to get help from people who know Java but don't know Scala Commented Nov 28, 2017 at 11:48
  • @Eran, I was not sure what that line of code did specifically but it is part of a larger section of code which is used to generate TOTP Auth codes. This one line I wasn't sure of what it was doing. Commented Nov 28, 2017 at 12:07

2 Answers 2

5

With a zero filler

String.format("%08d", value)

Mind should the long have more than 8 digits you get an overflow.

Sign up to request clarification or add additional context in comments.

2 Comments

I think your answer gives me exaclty what I need in terms of the actual Java 8 equivalent. value I believe will never be longer than 8 digits so no overflow should ever occur.
in Scala, f"$value%08d"
2
  • "0" * codeLength appends eight zeroes to one another.
  • after that value.toString is appended to the eight zeroes.
  • .takeRight(codeLength) takes the last codeLength (in this case - 8) characters from the resulting String. Which is value.toString.

So, I would guess that the Java equivalent would simply be:

String result = "12345678";

2 Comments

takeRight for the last 8.
In the Scala code value is a variable and NOT hardcoded to "12345678" (I should prob have mentioned that!). Your explanation makes it clear however that that line of code is used to fill in the value with zeroes in cases where value is shorter than codeLength.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.