Home > Software design >  Scala: checking String for only digits behaving strange
Scala: checking String for only digits behaving strange

Time:12-07

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?

CodePudding user response:

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)
  • Related