neil
neil

Reputation: 169

How to check whether an integer is present in the range in Scala?

I have to check whether 2 is present in the range (2,5) .

How do I check that using Scala?

Upvotes: 6

Views: 7742

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Ranges in Scala are created using the methods to and until:

  • 2 to 5 would give you inclusive-inclusive range with numbers 2,3,4,5
  • 2 until 5 would give you inclusive-exclusive range 2,3,4

Ranges provide the method contains to check for element membership, so

a to b contains x

would check whether x is in the range a to b, in your case, it would be

2 to 5 contains 2

if you wanted inclusive-inclusive, or

(2 + 1) until 5 contains 2

if you wanted exclusive-exclusive etc.

Upvotes: 14

Related Questions