Skip to content

Document comprehension based validation #10

Description

@carlpulley

Currently, validated-config uses the free structure of the case class ASTs to perform validation. In some validation scenarios, we may need to ensure (for example) that certain combinations of case class fields are acceptable (c.f. comprehension).

As a concrete example, imagine the following case class:

final case class Example(hostname: String, port: Int)

we may want port >= 0 in general, but when hostname matches localhost we want port >= 1024.

As we can achieve this functionality here by using flatMap on functions of type Example => Try[Example] - we need to ensure this type of usage is documented.

So, for the example code above, we'd write something like:

case object ShouldBePositive extends Exception
case object LocalhostPortShouldBeNonPrivileged extends Exception

validateConfig("application.conf") { implicit config =>
  build[Example](
    unchecked[String]("hostname"),
    validate[port]("port", ShouldBePositive)(_ >= 0)
  )
}.flatMap {
  case eg @ Example("localhost", port) if port >= 1024 =>
    Success(eg)
  case Example("localhost", _) =>
    Failure(LocalhostPortShouldBeNonPrivileged)
  case eg: Example =>
    Success(eg)
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions