scalarefinement-type

Refine a string to only certain values scala


Is there any way to refine a string to only a certain subset of values? For example, I have a list of 500 keys in a hash map. But I only want certain keys to be inserted. For example, "abcd" and "aaaa" are valid keys but "abdc" is invalid. Is there any way to refine the String to only one of the given 500 keys?

I'm guessing the way to do this is just a very long regexp that matches abcd|aaaa?

Edit: Using the fthomas/refined library specifically the MatchesRegex function. Want to know if there is a better approach that I'm missing out on.


Solution

  • Scala 3 seems to Allow Singletons in Unions #6299 like so

    val refinedString: "abcd" | "aaaa" = "aaaa"
    

    whilst abdc would result in the following error

    val refinedString: "abcd" | "aaaa" = "abdc"
                                         ^^^^^^
                               Found:    String("abdc")
                               Required: String("abcd") | String("aaaa")
    

    It worked for me with Dotty Scala version 0.15.0-bin-20190517-fb6667b-NIGHTLY.