HDev007
HDev007

Reputation: 325

Set specific range for int in scala

class Test(val myInt :Int){}

I want that for myInt only 0 to 10 must be allowed.So how to specify range for member variable in scala with val type.

Upvotes: 1

Views: 549

Answers (2)

soote
soote

Reputation: 3260

Give Refined a look. It allows you to create range types which are checked at compile time.

Your range would look like this:

type InMyRange = Interval.ClosedOpen[W.`0`.T, W.`10`.T]

and you can create a value of this type like so:

refineMV[InMyRange](0) 
// Refined[Int, InMyRange] = 0
refineMV[InMyRange](9) 
// Refined[Int, InMyRange] = 9

In the error cases:

refineMV[InMyRange](-1) 
// Left predicate of (!(-1 < 0) && (-1 < 10)) failed: Predicate (-1 < 0) did not fail
refineMV[InMyRange](10) 
// Right predicate of (!(10 < 0) && (10 < 10)) failed: Predicate failed: (10 < 10)

Upvotes: 3

suish
suish

Reputation: 3363

simply adding require or whatever which throws an exception when it gets invalid value solves your issue.

class Test(val myInt :Int){
  require(0 <= myInt && myInt <= 10)
}

Upvotes: 2

Related Questions