I'm still fairly new to Scala, and I'm discovering new and interesting ways for doing things on an almost daily basis, but they're not always sensible, and sometimes already exist within the language as a construct and I just don't know about them. So, with that preamble, I'm checking to see if a given string is comprised entirely of digits, so I'm doing:
def isAllDigits(x: String) = x.map(Character.isDigit(_)).reduce(_&&_)
is this sensible or just needlessly silly? It there a better way? Is it better just to call x.toInt and catch the exception, or is that less idiomatic? Is there a performance benefit/drawback to either?
Using Character.isDigit method returns true if the character is a number.
Use the contains() Function to Find Substring in Scala Here, we used the contains() function to find the substring in a string. This function returns a Boolean value, either true or false.
Try this:
def isAllDigits(x: String) = x forall Character.isDigit
forall
takes a function (in this case Character.isDigit
) that takes an argument that is of the type of the elements of the collection and returns a Boolean
; it returns true
if the function returns true
for all elements in the collection, and false
otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With