Scala: Can we combine protection conditions with matching patterns in front in a class declaration of a private class

Is it possible to combine protection conditions with pattern matching in a class declaration of a private class?

I understand that you can include defensive conditions in the conformance block, but I believe that it would be useful to define these conditions in front in closed class classes. This will allow developers to define a strict set of possible inputs that the compiler will check when matching patterns.

So, I would like to do something like this:

// create a set of pattern matchable cases with guards built in sealed abstract class Args case class ValidArgs1(arg1:Int,arg2:Int) if arg1>1 && arg2<10 extends Args case class ValidArgs2(arg1:Int,arg2:Int) if arg1>5 && arg2<6 extends Args case class InvalidArgs(arg1:Int,arg2:Int) if arg1<=1 && arg2>=10 extends Args // the aim of this is to achieve pattern matching against an exhaustive set of // pre-defined possibilities def process(args:Args){ args match { case ValidArgs1 = > // do this case ValidArgs2= > // do this case InvalidArgs = > // do this } } 
+7
source share
2 answers

+1 for an interesting speculative question. Since you are not working at the type level, you cannot check the instance at compile time, with the possible exception of special checks using macros, for example. when you pass literals to the constructor.

Your script, pattern matching, on the other hand, is a run-time action. For this you can use extractors instead of case classes.

 case class Args(arg1: Int, arg2: Int) object ValidArgs1 { def apply(arg1: Int, arg2: Int): Args = { val res = Args(arg1, arg2) require(unapply(res)) res } def unapply(args: Args): Boolean = args.arg1 > 1 && args.arg2 < 10 } def process(args: Args) = args match { case ValidArgs1() => "ok" case _ => "invalid" } process(ValidArgs1(2, 9)) process(Args(1, 10)) process(Args(3, 4)) 
+6
source

I do not believe that you can have common restrictions / statements that are checked at compile time in Scala, because Scala does not have the static verifier that is needed for this. If you're interested, check out (research) languages ​​/ tools such as ESC / Java , SpeC # , Dafny, or VeriFast .

There may be ways with a very limited amount of static checking using a regular Scala compiler using level programming at a level or Scala , but this is just a wild hunch about mine, as I am not familiar with any of them. Honestly, I have to admit that I would be very surprised if macros really help here.

What does run-time validation check work, for example

 case class Foo(arg1: Int, arg2: Int) { require(arg1 < arg2, "The first argument must be strictly less than " + "the second argument.") } Foo(0, 0) /* java.lang.IllegalArgumentException: requirement failed: * The first argument must be strictly less than the second * argument. */ 

but that’s not what you had in mind.

-one
source

All Articles