Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala: checking String for only digits behaving strange

I wrote the code, which works as expected, when I apply for entrance not empty string with only digits or with not only digits:

   def checkDigits(nameOrId: String): Unit = {

      def isAllDigits(x: String) = x forall (c => c.isDigit)

      if (isAllDigits(nameOrId)) print("WITH_ID ")
      else print("WITH_NAME")
  }

But when I apply for entrance ""-value, it print no "WITH_NAME", but "WITH_ID ". So it recognize "" as digit-character!

What am I doing wrong and how could I improve my code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The forall method checks whether a test is true for all values in a collection. If there are no values it returns true, because all the values pass the test.

For the behaviour you want you need to add an extra test:

def isAllDigits(x: String) = x.nonEmpty && x.forall(_.isDigit)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading