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?)
2 Answers
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)
Comments
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
if (mystring.isEmpty) 0 else mystring.toInt. I'm sure you realize the other edge cases there.util.Try{"".toInt}.getOrElse(0)