3

The refined library allows to define refinement that matches a given regex, as shown in the Readme:

import eu.timepit.refined._
import eu.timepit.refined.string._
import eu.timepit.refined.api.Refined

type MyType = String Refined MatchesRegex[W.`"[0-9]+"`.T]

While this works perfectly fine, we can't define this way a type that matches a regex containing a backtick, because as describe here there is no way to escape a backtick within a literal:

 type MyType = String Refined MatchesRegex[W.`"(a|`)"`.T]

 // Getting a compile-error:
 // ']' expected but ')' found.

So would there be a way to define such a type (i.e MatchesRegex with a regex containing a backtick)?

Valy Dia
  • 2,781
  • 2
  • 12
  • 32

1 Answers1

2

A way to do so is to use singleton types available in Scala 2.13 or Typelevel Scala.

For Typelevel Scala, you need to add / replace in your build.sbt:

scalaOrganization := "org.typelevel",
scalaVersion := "2.12.4-bin-typelevel-4", // Assuming you are using scala 2.12

And you need to add the compiler flag -Yliteral-types:

scalacOptions := Seq(
                  ..., // Other options
                  "-Yliteral-types"
                 )

And now the refined type can simply be:

import eu.timepit.refined._
import eu.timepit.refined.api.Refined

type MyType = String Refined MatchesRegex["""(a|`)"""]
Valy Dia
  • 2,781
  • 2
  • 12
  • 32