Jelly
Jelly

Reputation: 1300

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?

Upvotes: 0

Views: 51

Answers (2)

The fourth bird
The fourth bird

Reputation: 163467

The regex alternative is using matches which should match the whole string and match for 1 or more digits.

Note that your method def checkDigits returns Unit because you are only printing. To make it return a boolean you can use:

def checkDigits(x: String) = x.matches("\\d+")

Upvotes: 0

Tim
Tim

Reputation: 27421

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)

Upvotes: 2

Related Questions