Compile Time Method Parameter Constraints


#1

Is there a way, at compile time, to ensure that a parameter meets certain requirements?
i.e.

//i is type Int within the range 11-53 inclusive
def x(i: Int[Range(11,53)]) == ???

I’ve seen where it can be done with type level programming, but the examples I found only seemed practical with a very limited number of acceptable values.


#2

I’d recommend Refined:

def x(i: Int Refined Interval.Closed[W.`11`.T, W.`53`.T]) = ???

#3

Thanks. That is awesome!


#4

There are also several runtime validation frameworks that have similar
effect.

I have used Scalaz Validation + Tagged types and have been very satisfied
with the results. This is the primary way I work with weakly-typed JSON or
other graph-like structures in a couple projects, and it ends up working
nicely. My code can pass around tagged weakly-typed values without the need
for value-checking all over the place, and also without the overhead of
isomorphic translations to strongly-typed domain classes.

I imagine I would be able to do effectively the same thing with Refined as
well. Refined is just not a library/idiom I’m as comfortable with.

Brian Maso


#5

Thanks,

I’ll definitely give Scalaz Validation + Tagged a look as well.