Reputation: 325
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
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
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