0

scala has the mystring.toInt method to convert string to int but this doesn't work on empty string. Is it possible to convert empty strings to a default int value? (say 0?)

3
  • 1
    if (mystring.isEmpty) 0 else mystring.toInt. I'm sure you realize the other edge cases there. Commented Dec 11, 2018 at 19:35
  • 2
    util.Try{"".toInt}.getOrElse(0) Commented Dec 11, 2018 at 19:46
  • Checkout my one-line code answer: stackoverflow.com/a/77739302/4621922 Commented Dec 31, 2023 at 17:41

2 Answers 2

2

You want to use String.toInt() as you know that you have something that is convertible to int :

Parse as an Int (string must contain only decimal digits and optional leading -).

So the method doesn't provide a default value.

Generally you can do this processing by checking that the String contains only digits in this way :

val a : Int = if (mystring.forall(Character.isDigit))  mystring.toInt else 0

But in your case (empty string) this is enough :

val a : Int =
      if (mystring.isEmpty) 0
      else mystring.toInt

Or you can also catch the exception such as :

import scala.util.Try;
...
val a : Int = Try(mystring.toInt).getOrElse(0)
Sign up to request clarification or add additional context in comments.

Comments

1

One solution is to always prepend whatever string you're given with "0" before calling toInt:

("0" + myString).toInt

When myString is "", the result is 0.

When myString is "123", the result is 123.

When myString is "123a", the result is an exception, since toInt does the checking for you.

Just out of curiosity to see how the string concatenation performs in comparison, using:

def makeAnInt(myString: String): Int = ("0" + myString).toInt
def makeAnInt2(mystring: String): Int = if (mystring.isEmpty) 0 else mystring.toInt
def makeAnInt3(mystring: String): Int = Try(mystring.toInt).getOrElse(0)

Generated:

1M calls with "":
("0" + myString).toInt -> 250ms
if (mystring.isEmpty) 0 else mystring.toInt -> 156ms
Try(mystring.toInt).getOrElse(0) -> 1481ms

1M calls with "123":
("0" + myString).toInt -> 251ms
if (mystring.isEmpty) 0 else mystring.toInt -> 188ms
Try(mystring.toInt).getOrElse(0) -> 198ms

Comments

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.