o

catslib

ValidatedSection

object ValidatedSection extends AnyFlatSpec with Matchers with Section

Imagine you are filling out a web form to sign up for an account. You input your username and password and submit. Response comes back saying your username can't have dashes in it, so you make some changes and resubmit. Can't have special characters either. Change, resubmit. Passwords need to have at least one capital letter. Change, resubmit. Password needs to have at least one number.

Or perhaps you're reading from a configuration file. One could imagine the configuration library you're using returns a scala.util.Try, or maybe a scala.util.Either. Your parsing may look something like:

case class ConnectionParams(url: String, port: Int)

for {
url  <- config[String]("url")
port <- config[Int]("port")
} yield ConnectionParams(url, port)

You run your program and it says key "url" not found, turns out the key was "endpoint". So you change your code and re-run. Now it says the "port" key was not a well-formed integer.

It would be nice to have all of these errors reported simultaneously. That the username can't have dashes can be validated separately from it not having special characters, as well as from the password needing to have certain requirements. A misspelled (or missing) field in a config can be validated separately from another field not being well-formed.

Enter Validated.

Parallel validation

Our goal is to report any and all errors across independent bits of data. For instance, when we ask for several pieces of configuration, each configuration field can be validated separately from one another. How then do we enforce that the data we are working with is independent? We ask for both of them up front.

As our running example, we will look at config parsing. Our config will be represented by a Map[String, String]. Parsing will be handled by a Read type class - we provide instances only for String and Int for brevity.

trait Read[A] {
def read(s: String): Option[A]
}

object Read {
def apply[A](implicit A: Read[A]): Read[A] = A

implicit val stringRead: Read[String] =
 new Read[String] { def read(s: String): Option[String] = Some(s) }

implicit val intRead: Read[Int] =
 new Read[Int] {
   def read(s: String): Option[Int] =
     if (s.matches("-?[0-9]+")) Some(s.toInt)
     else None
 }
}

Then we enumerate our errors—when asking for a config value, one of two things can go wrong: the field is missing, or it is not well-formed with regards to the expected type.

sealed abstract class ConfigError
final case class MissingConfig(field: String) extends ConfigError
final case class ParseError(field: String) extends ConfigError

We need a data type that can represent either a successful value (a parsed configuration), or an error. It would look like the following, which cats provides in cats.data.Validated:

sealed abstract class Validated[+E, +A]

object Validated {
final case class Valid[+A](a: A) extends Validated[Nothing, A]
final case class Invalid[+E](e: E) extends Validated[E, Nothing]
}

Now we are ready to write our parser.

import cats.data.Validated
import cats.data.Validated.{Invalid, Valid}

case class Config(map: Map[String, String]) {
def parse[A : Read](key: String): Validated[ConfigError, A] =
 map.get(key) match {
   case None        => Invalid(MissingConfig(key))
   case Some(value) =>
     Read[A].read(value) match {
       case None    => Invalid(ParseError(key))
       case Some(a) => Valid(a)
     }
 }
}

Everything is in place to write the parallel validator. Recall that we can only do parallel validation if each piece is independent. How do we enforce the data is independent? By asking for all of it up front. Let's start with two pieces of data.

def parallelValidate[E, A, B, C](v1: Validated[E, A], v2: Validated[E, B])(f: (A, B) => C): Validated[E, C] =
(v1, v2) match {
 case (Valid(a), Valid(b))       => Valid(f(a, b))
 case (Valid(_), i@Invalid(_))   => i
 case (i@Invalid(_), Valid(_))   => i
 case (Invalid(e1), Invalid(e2)) => ???
}

We've run into a problem. In the case where both have errors, we want to report both. But we have no way of combining the two errors into one error! Perhaps we can put both errors into a List, but that seems needlessly specific—clients may want to define their own way of combining errors.

How then do we abstract over a binary operation? The Semigroup type class captures this idea.

import cats.Semigroup

def parallelValidate[E : Semigroup, A, B, C](v1: Validated[E, A], v2: Validated[E, B])(f: (A, B) => C): Validated[E, C] =
(v1, v2) match {
 case (Valid(a), Valid(b))       => Valid(f(a, b))
 case (Valid(_), i@Invalid(_))   => i
 case (i@Invalid(_), Valid(_))   => i
 case (Invalid(e1), Invalid(e2)) => Invalid(Semigroup[E].combine(e1, e2))
}

Perfect! But, going back to our example, we don't have a way to combine ConfigErrors. But as clients, we can change our Validated values where the error can be combined, say, a List[ConfigError]. It is more common however to use a NonEmptyList[ConfigError]—the NonEmptyList statically guarantees we have at least one value, which aligns with the fact that if we have an Invalid, then we most certainly have at least one error. This technique is so common there is a convenient method on Validated called toValidatedNel that turns any Validated[E, A] value to a Validated[NonEmptyList[E], A]. Additionally, the type alias ValidatedNel[E, A] is provided.

Time to parse.

import cats.SemigroupK
import cats.data.NonEmptyList
import cats.implicits._

implicit val nelSemigroup: Semigroup[NonEmptyList[ConfigError]] =
SemigroupK[NonEmptyList].algebra[ConfigError]

implicit val readString: Read[String] = Read.stringRead
implicit val readInt: Read[Int] = Read.intRead
Linear Supertypes
Section, Matchers, Explicitly, MatcherWords, Tolerance, AnyFlatSpec, AnyFlatSpecLike, Documenting, Alerting, Notifying, Informing, CanVerb, MustVerb, ShouldVerb, TestRegistration, TestSuite, Suite, Serializable, Assertions, TripleEquals, TripleEqualsSupport, AnyRef, Any
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. ValidatedSection
  2. Section
  3. Matchers
  4. Explicitly
  5. MatcherWords
  6. Tolerance
  7. AnyFlatSpec
  8. AnyFlatSpecLike
  9. Documenting
  10. Alerting
  11. Notifying
  12. Informing
  13. CanVerb
  14. MustVerb
  15. ShouldVerb
  16. TestRegistration
  17. TestSuite
  18. Suite
  19. Serializable
  20. Assertions
  21. TripleEquals
  22. TripleEqualsSupport
  23. AnyRef
  24. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. Protected

Type Members

  1. final class AWord extends AnyRef
    Definition Classes
    Matchers
  2. final class AnWord extends AnyRef
    Definition Classes
    Matchers
  3. sealed class AnyShouldWrapper[T] extends AnyRef
    Definition Classes
    Matchers
  4. final class BehaviorWord extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  5. class CheckingEqualizer[L] extends AnyRef
    Definition Classes
    TripleEqualsSupport
  6. sealed class Collected extends Serializable
    Attributes
    protected
    Definition Classes
    Matchers
  7. class DecidedByEquality[A] extends Equality[A]
    Definition Classes
    Explicitly
  8. class DecidedWord extends AnyRef
    Definition Classes
    Explicitly
  9. class DeterminedByEquivalence[T] extends Equivalence[T]
    Definition Classes
    Explicitly
  10. class DeterminedWord extends AnyRef
    Definition Classes
    Explicitly
  11. class Equalizer[L] extends AnyRef
    Definition Classes
    TripleEqualsSupport
  12. final class HavePropertyMatcherGenerator extends AnyRef
    Definition Classes
    Matchers
  13. final class IgnoreVerbString extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  14. final class IgnoreVerbStringTaggedAs extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  15. final class IgnoreWord extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  16. final class InAndIgnoreMethods extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  17. final class InAndIgnoreMethodsAfterTaggedAs extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  18. final class ItVerbString extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  19. final class ItVerbStringTaggedAs extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  20. final class ItWord extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  21. final class KeyWord extends AnyRef
    Definition Classes
    Matchers
  22. trait NoArgTest extends () => Outcome with TestData
    Attributes
    protected
    Definition Classes
    TestSuite
  23. final class PlusOrMinusWrapper[T] extends AnyRef
    Definition Classes
    Tolerance
  24. final class RegexWord extends AnyRef
    Definition Classes
    Matchers
  25. final class RegexWrapper extends AnyRef
    Definition Classes
    Matchers
  26. class ResultOfBeWordForAny[T] extends AnyRef
    Definition Classes
    Matchers
  27. sealed class ResultOfBeWordForCollectedAny[T] extends AnyRef
    Definition Classes
    Matchers
  28. final class ResultOfBeWordForCollectedArray[T] extends ResultOfBeWordForCollectedAny[Array[T]]
    Definition Classes
    Matchers
  29. final class ResultOfCollectedAny[T] extends AnyRef
    Definition Classes
    Matchers
  30. final class ResultOfContainWordForCollectedAny[T] extends AnyRef
    Definition Classes
    Matchers
  31. final class ResultOfEndWithWordForCollectedString extends AnyRef
    Definition Classes
    Matchers
  32. final class ResultOfEndWithWordForString extends AnyRef
    Definition Classes
    Matchers
  33. final class ResultOfFullyMatchWordForCollectedString extends AnyRef
    Definition Classes
    Matchers
  34. final class ResultOfFullyMatchWordForString extends AnyRef
    Definition Classes
    Matchers
  35. final class ResultOfHaveWordForCollectedExtent[A] extends AnyRef
    Definition Classes
    Matchers
  36. final class ResultOfHaveWordForExtent[A] extends AnyRef
    Definition Classes
    Matchers
  37. final class ResultOfIncludeWordForCollectedString extends AnyRef
    Definition Classes
    Matchers
  38. final class ResultOfIncludeWordForString extends AnyRef
    Definition Classes
    Matchers
  39. final class ResultOfNotWordForCollectedAny[T] extends AnyRef
    Definition Classes
    Matchers
  40. final class ResultOfStartWithWordForCollectedString extends AnyRef
    Definition Classes
    Matchers
  41. final class ResultOfStartWithWordForString extends AnyRef
    Definition Classes
    Matchers
  42. trait StringCanWrapperForVerb extends AnyRef
    Definition Classes
    CanVerb
  43. trait StringMustWrapperForVerb extends AnyRef
    Definition Classes
    MustVerb
  44. final class StringShouldWrapper extends AnyShouldWrapper[String] with org.scalatest.matchers.should.Matchers.StringShouldWrapperForVerb
    Definition Classes
    Matchers
  45. trait StringShouldWrapperForVerb extends AnyRef
    Definition Classes
    ShouldVerb
  46. class TheAfterWord extends AnyRef
    Definition Classes
    Explicitly
  47. final class TheSameInstanceAsPhrase extends AnyRef
    Definition Classes
    Matchers
  48. final class TheyVerbString extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  49. final class TheyVerbStringTaggedAs extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  50. final class TheyWord extends AnyRef
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  51. final class ValueWord extends AnyRef
    Definition Classes
    Matchers

Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. def !==[T](right: Spread[T]): TripleEqualsInvocationOnSpread[T]
    Definition Classes
    TripleEqualsSupport
  3. def !==(right: Null): TripleEqualsInvocation[Null]
    Definition Classes
    TripleEqualsSupport
  4. def !==[T](right: T): TripleEqualsInvocation[T]
    Definition Classes
    TripleEqualsSupport
  5. final def ##: Int
    Definition Classes
    AnyRef → Any
  6. def <[T](right: T)(implicit arg0: Ordering[T]): ResultOfLessThanComparison[T]
    Definition Classes
    Matchers
  7. def <=[T](right: T)(implicit arg0: Ordering[T]): ResultOfLessThanOrEqualToComparison[T]
    Definition Classes
    Matchers
  8. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  9. def ===[T](right: Spread[T]): TripleEqualsInvocationOnSpread[T]
    Definition Classes
    TripleEqualsSupport
  10. def ===(right: Null): TripleEqualsInvocation[Null]
    Definition Classes
    TripleEqualsSupport
  11. def ===[T](right: T): TripleEqualsInvocation[T]
    Definition Classes
    TripleEqualsSupport
  12. def >[T](right: T)(implicit arg0: Ordering[T]): ResultOfGreaterThanComparison[T]
    Definition Classes
    Matchers
  13. def >=[T](right: T)(implicit arg0: Ordering[T]): ResultOfGreaterThanOrEqualToComparison[T]
    Definition Classes
    Matchers
  14. def a[T](implicit arg0: ClassTag[T]): ResultOfATypeInvocation[T]
    Definition Classes
    Matchers
  15. val a: AWord
    Definition Classes
    Matchers
  16. val after: TheAfterWord
    Definition Classes
    Explicitly
  17. def alert: Alerter
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike → Alerting
  18. def all(xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  19. def all[K, V, JMAP[k, v] <: Map[k, v]](xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  20. def all[K, V, MAP[k, v] <: GenMap[k, v]](xs: MAP[K, V])(implicit collecting: Collecting[(K, V), GenTraversable[(K, V)]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[(K, V)]
    Definition Classes
    Matchers
  21. def all[E, C[_]](xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  22. def allElementsOf[R](elements: GenTraversable[R]): ResultOfAllElementsOfApplication
    Definition Classes
    Matchers
  23. def allOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfAllOfApplication
    Definition Classes
    Matchers
  24. def an[T](implicit arg0: ClassTag[T]): ResultOfAnTypeInvocation[T]
    Definition Classes
    Matchers
  25. val an: AnWord
    Definition Classes
    Matchers
  26. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  27. macro def assert(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
    Definition Classes
    Assertions
  28. macro def assert(condition: Boolean)(implicit prettifier: Prettifier, pos: Position): Assertion
    Definition Classes
    Assertions
  29. macro def assertCompiles(code: String)(implicit pos: Position): Assertion
    Definition Classes
    Assertions
  30. macro def assertDoesNotCompile(code: String)(implicit pos: Position): Assertion
    Definition Classes
    Assertions
  31. def assertResult(expected: Any)(actual: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
    Definition Classes
    Assertions
  32. def assertResult(expected: Any, clue: Any)(actual: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
    Definition Classes
    Assertions
  33. def assertThrows[T <: AnyRef](f: => Any)(implicit classTag: ClassTag[T], pos: Position): Assertion
    Definition Classes
    Assertions
  34. macro def assertTypeError(code: String)(implicit pos: Position): Assertion
    Definition Classes
    Assertions
  35. macro def assume(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: Position): Assertion
    Definition Classes
    Assertions
  36. macro def assume(condition: Boolean)(implicit prettifier: Prettifier, pos: Position): Assertion
    Definition Classes
    Assertions
  37. def atLeast(num: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  38. def atLeast[K, V, JMAP[k, v] <: Map[k, v]](num: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  39. def atLeast[K, V, MAP[k, v] <: GenMap[k, v]](num: Int, xs: MAP[K, V])(implicit collecting: Collecting[(K, V), GenTraversable[(K, V)]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[(K, V)]
    Definition Classes
    Matchers
  40. def atLeast[E, C[_]](num: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  41. def atLeastOneElementOf(elements: GenTraversable[Any]): ResultOfAtLeastOneElementOfApplication
    Definition Classes
    Matchers
  42. def atLeastOneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfAtLeastOneOfApplication
    Definition Classes
    Matchers
  43. def atMost(num: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  44. def atMost[K, V, JMAP[k, v] <: Map[k, v]](num: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  45. def atMost[K, V, MAP[k, v] <: GenMap[k, v]](num: Int, xs: MAP[K, V])(implicit collecting: Collecting[(K, V), GenTraversable[(K, V)]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[(K, V)]
    Definition Classes
    Matchers
  46. def atMost[E, C[_]](num: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  47. def atMostOneElementOf[R](elements: GenTraversable[R]): ResultOfAtMostOneElementOfApplication
    Definition Classes
    Matchers
  48. def atMostOneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfAtMostOneOfApplication
    Definition Classes
    Matchers
  49. val be: BeWord
    Definition Classes
    MatcherWords
  50. val behave: BehaveWord
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  51. val behavior: BehaviorWord
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  52. def between(from: Int, upTo: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  53. def between[K, V, JMAP[k, v] <: Map[k, v]](from: Int, upTo: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  54. def between[E, C[_]](from: Int, upTo: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  55. def cancel(cause: Throwable)(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  56. def cancel(message: String, cause: Throwable)(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  57. def cancel(message: String)(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  58. def cancel()(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  59. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.CloneNotSupportedException]) @native()
  60. val compile: CompileWord
    Definition Classes
    MatcherWords
  61. val contain: ContainWord
    Definition Classes
    MatcherWords
  62. def convertEquivalenceToAToBConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: <:<[A, B]): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  63. def convertEquivalenceToBToAConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: <:<[B, A]): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  64. implicit def convertNumericToPlusOrMinusWrapper[T](pivot: T)(implicit arg0: Numeric[T]): PlusOrMinusWrapper[T]
    Definition Classes
    Tolerance
  65. implicit def convertSymbolToHavePropertyMatcherGenerator(symbol: Symbol)(implicit prettifier: Prettifier, pos: Position): HavePropertyMatcherGenerator
    Definition Classes
    Matchers
  66. implicit def convertToAnyShouldWrapper[T](o: T)(implicit pos: Position, prettifier: Prettifier): AnyShouldWrapper[T]
    Definition Classes
    Matchers
  67. def convertToCheckingEqualizer[T](left: T): CheckingEqualizer[T]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  68. implicit def convertToEqualizer[T](left: T): Equalizer[T]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  69. implicit def convertToInAndIgnoreMethods(resultOfStringPassedToVerb: ResultOfStringPassedToVerb): InAndIgnoreMethods
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  70. implicit def convertToInAndIgnoreMethodsAfterTaggedAs(resultOfTaggedAsInvocation: ResultOfTaggedAsInvocation): InAndIgnoreMethodsAfterTaggedAs
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  71. implicit def convertToRegexWrapper(o: Regex): RegexWrapper
    Definition Classes
    Matchers
  72. implicit def convertToStringCanWrapper(o: String)(implicit position: Position): StringCanWrapperForVerb
    Definition Classes
    CanVerb
  73. implicit def convertToStringMustWrapperForVerb(o: String)(implicit position: Position): StringMustWrapperForVerb
    Definition Classes
    MustVerb
  74. implicit def convertToStringShouldWrapper(o: String)(implicit pos: Position, prettifier: Prettifier): StringShouldWrapper
    Definition Classes
    Matchers
  75. implicit def convertToStringShouldWrapperForVerb(o: String)(implicit position: Position): StringShouldWrapperForVerb
    Definition Classes
    ShouldVerb
  76. val decided: DecidedWord
    Definition Classes
    Explicitly
  77. def defaultEquality[A]: Equality[A]
    Definition Classes
    TripleEqualsSupport
  78. val defined: DefinedWord
    Definition Classes
    MatcherWords
  79. def definedAt[T](right: T): ResultOfDefinedAt[T]
    Definition Classes
    Matchers
  80. val determined: DeterminedWord
    Definition Classes
    Explicitly
  81. val empty: EmptyWord
    Definition Classes
    MatcherWords
  82. val endWith: EndWithWord
    Definition Classes
    MatcherWords
  83. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  84. def equal(o: Null): Matcher[AnyRef]
    Definition Classes
    Matchers
  85. def equal[T](spread: Spread[T]): Matcher[T]
    Definition Classes
    Matchers
  86. def equal(right: Any): MatcherFactory1[Any, Equality]
    Definition Classes
    MatcherWords
  87. def equals(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef → Any
  88. def every(xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  89. def every[K, V, JMAP[k, v] <: Map[k, v]](xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  90. def every[K, V, MAP[k, v] <: Map[k, v]](xs: MAP[K, V])(implicit collecting: Collecting[(K, V), GenTraversable[(K, V)]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[(K, V)]
    Definition Classes
    Matchers
  91. def every[E, C[_]](xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  92. def exactly(num: Int, xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  93. def exactly[K, V, JMAP[k, v] <: Map[k, v]](num: Int, xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  94. def exactly[K, V, MAP[k, v] <: GenMap[k, v]](num: Int, xs: MAP[K, V])(implicit collecting: Collecting[(K, V), GenTraversable[(K, V)]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[(K, V)]
    Definition Classes
    Matchers
  95. def exactly[E, C[_]](num: Int, xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  96. final def execute(testName: String, configMap: ConfigMap, color: Boolean, durations: Boolean, shortstacks: Boolean, fullstacks: Boolean, stats: Boolean): Unit
    Definition Classes
    Suite
  97. val exist: ExistWord
    Definition Classes
    MatcherWords
  98. def expectedTestCount(filter: Filter): Int
    Definition Classes
    Suite
  99. def fail(cause: Throwable)(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  100. def fail(message: String, cause: Throwable)(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  101. def fail(message: String)(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  102. def fail()(implicit pos: Position): Nothing
    Definition Classes
    Assertions
  103. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.Throwable])
  104. val fullyMatch: FullyMatchWord
    Definition Classes
    MatcherWords
  105. final def getClass(): Class[_ <: AnyRef]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  106. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  107. val have: HaveWord
    Definition Classes
    MatcherWords
  108. val ignore: IgnoreWord
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  109. def inOrder(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfInOrderApplication
    Definition Classes
    Matchers
  110. def inOrderElementsOf[R](elements: GenTraversable[R]): ResultOfInOrderElementsOfApplication
    Definition Classes
    Matchers
  111. def inOrderOnly[T](firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfInOrderOnlyApplication
    Definition Classes
    Matchers
  112. val include: IncludeWord
    Definition Classes
    MatcherWords
  113. def info: Informer
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike → Informing
  114. def intercept[T <: AnyRef](f: => Any)(implicit classTag: ClassTag[T], pos: Position): T
    Definition Classes
    Assertions
  115. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  116. val it: ItWord
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  117. val key: KeyWord
    Definition Classes
    Matchers
  118. val length: LengthWord
    Definition Classes
    MatcherWords
  119. def lowPriorityTypeCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], ev: <:<[A, B]): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  120. def markup: Documenter
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike → Documenting
  121. val matchPattern: MatchPatternWord
    Definition Classes
    MatcherWords
  122. def message(expectedMessage: String): ResultOfMessageWordApplication
    Definition Classes
    Matchers
  123. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  124. def nestedSuites: IndexedSeq[Suite]
    Definition Classes
    Suite
  125. def no(xs: String)(implicit collecting: Collecting[Char, String], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Char]
    Definition Classes
    Matchers
  126. def no[K, V, JMAP[k, v] <: Map[k, v]](xs: JMAP[K, V])(implicit collecting: Collecting[Entry[K, V], JMAP[K, V]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[Entry[K, V]]
    Definition Classes
    Matchers
  127. def no[E, C[_]](xs: C[E])(implicit collecting: Collecting[E, C[E]], prettifier: Prettifier, pos: Position): ResultOfCollectedAny[E]
    Definition Classes
    Matchers
  128. def noElementsOf(elements: GenTraversable[Any]): ResultOfNoElementsOfApplication
    Definition Classes
    Matchers
  129. def noErrors(res0: Boolean, res1: String, res2: Int): Assertion

    When no errors are present in the configuration, we get a ConnectionParams wrapped in a Valid instance.

  130. def noException(implicit pos: Position): NoExceptionWord
    Definition Classes
    MatcherWords
  131. def noneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfNoneOfApplication
    Definition Classes
    Matchers
  132. val not: NotWord
    Definition Classes
    MatcherWords
  133. def note: Notifier
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike → Notifying
  134. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  135. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  136. def of[T](implicit ev: ClassTag[T]): ResultOfOfTypeInvocation[T]
    Definition Classes
    Matchers
  137. def oneElementOf(elements: GenTraversable[Any]): ResultOfOneElementOfApplication
    Definition Classes
    Matchers
  138. def oneOf(firstEle: Any, secondEle: Any, remainingEles: Any*)(implicit pos: Position): ResultOfOneOfApplication
    Definition Classes
    Matchers
  139. def only(xs: Any*)(implicit pos: Position): ResultOfOnlyApplication
    Definition Classes
    Matchers
  140. def pending: Assertion with PendingStatement
    Definition Classes
    Assertions
  141. def pendingUntilFixed(f: => Unit)(implicit pos: Position): Assertion with PendingStatement
    Definition Classes
    Assertions
  142. val readable: ReadableWord
    Definition Classes
    MatcherWords
  143. val regex: RegexWord
    Definition Classes
    Matchers
  144. final def registerIgnoredTest(testText: String, testTags: Tag*)(testFun: => Any)(implicit pos: Position): Unit
    Definition Classes
    AnyFlatSpecLike → TestRegistration
  145. final def registerTest(testText: String, testTags: Tag*)(testFun: => Any)(implicit pos: Position): Unit
    Definition Classes
    AnyFlatSpecLike → TestRegistration
  146. def rerunner: Option[String]
    Definition Classes
    Suite
  147. def run(testName: Option[String], args: Args): Status
    Definition Classes
    AnyFlatSpecLike → Suite
  148. def runNestedSuites(args: Args): Status
    Attributes
    protected
    Definition Classes
    Suite
  149. def runTest(testName: String, args: Args): Status
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike → TestSuite → Suite
  150. def runTests(testName: Option[String], args: Args): Status
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike → Suite
  151. def sequentialValidation(res0: Boolean, res1: Boolean): Assertion

    Our parallelValidate function looks awfully like the Apply#map2 function.

    Apply

    Our parallelValidate function looks awfully like the Apply#map2 function.

    def map2[F[_], A, B, C](fa: F[A], fb: F[B])(f: (A, B) => C): F[C]

    Which can be defined in terms of Apply#ap and Apply#map, the very functions needed to create an Apply instance.

    Can we perhaps define an Apply instance for Validated? Better yet, can we define an Applicative instance?

    import cats.Applicative
    
    implicit def validatedApplicative[E : Semigroup]: Applicative[Validated[E, *]] =
    new Applicative[Validated[E, *]] {
     def ap[A, B](f: Validated[E, A => B])(fa: Validated[E, A]): Validated[E, B] =
       (fa, f) match {
         case (Valid(a), Valid(fab)) => Valid(fab(a))
         case (i@Invalid(_), Valid(_)) => i
         case (Valid(_), i@Invalid(_)) => i
         case (Invalid(e1), Invalid(e2)) => Invalid(Semigroup[E].combine(e1, e2))
       }
    
     def pure[A](x: A): Validated[E, A] = Validated.valid(x)
     def map[A, B](fa: Validated[E, A])(f: A => B): Validated[E, B] = fa.map(f)
     def product[A, B](fa: Validated[E, A], fb: Validated[E, B]): Validated[E, (A, B)] =
       ap(fa.map(a => (b: B) => (a, b)))(fb)
    }

    Awesome! And now we also get access to all the goodness of Applicative, which includes map{2-22}, as well as the Cartesian syntax |@|.

    We can now easily ask for several bits of configuration and get any and all errors returned back.

    import cats.Apply
    import cats.data.ValidatedNel
    
    implicit val nelSemigroup: Semigroup[NonEmptyList[ConfigError]] =
    SemigroupK[NonEmptyList].algebra[ConfigError]
    
    val config = Config(Map(("name", "cat"), ("age", "not a number"), ("houseNumber", "1234"), ("lane", "feline street")))
    
    case class Address(houseNumber: Int, street: String)
    case class Person(name: String, age: Int, address: Address)

    Thus.

    val personFromConfig: ValidatedNel[ConfigError, Person] =
    Apply[ValidatedNel[ConfigError, *]].map4(config.parse[String]("name").toValidatedNel,
                                            config.parse[Int]("age").toValidatedNel,
                                            config.parse[Int]("house_number").toValidatedNel,
                                            config.parse[String]("street").toValidatedNel) {
     case (name, age, houseNumber, street) => Person(name, age, Address(houseNumber, street))
    }

    We can now rewrite validations in terms of Apply.

    Of flatMaps and Eithers

    Option has flatMap, Either has flatMap, where's Validated's? Let's try to implement it—better yet, let's implement the Monad type class.

    import cats.Monad
    
    implicit def validatedMonad[E]: Monad[Validated[E, *]] =
    new Monad[Validated[E, *]] {
     def flatMap[A, B](fa: Validated[E, A])(f: A => Validated[E, B]): Validated[E, B] =
       fa match {
         case Valid(a)     => f(a)
         case i@Invalid(_) => i
       }
    
     def pure[A](x: A): Validated[E, A] = Valid(x)
    }

    Note that all Monad instances are also Applicative instances, where ap is defined as

    trait Monad[F[_]] {
    def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
    def pure[A](x: A): F[A]
    
    def map[A, B](fa: F[A])(f: A => B): F[B] =
     flatMap(fa)(f.andThen(pure))
    
    def ap[A, B](fa: F[A])(f: F[A => B]): F[B] =
     flatMap(fa)(a => map(f)(fab => fab(a)))
    }

    However, the ap behavior defined in terms of flatMap does not behave the same as that of our ap defined above. Observe:

    val v = validatedMonad.tuple2(Validated.invalidNel[String, Int]("oops"), Validated.invalidNel[String, Double]("uh oh"))

    This one short circuits! Therefore, if we were to define a Monad (or FlatMap) instance for Validated we would have to override ap to get the behavior we want. But then the behavior of flatMap would be inconsistent with that of ap, not good. Therefore, Validated has only an Applicative instance.

    Sequential Validation

    If you do want error accumulation but occasionally run into places where sequential validation is needed, then Validated provides a couple methods that may be helpful.

    andThen

    The andThen method is similar to flatMap (such as Either.flatMap). In the case of success, it passes the valid value into a function that returns a new Validated instance.

    val houseNumber = config.parse[Int]("house_number").andThen{ n =>
    if (n >= 0) Validated.valid(n)
    else Validated.invalid(ParseError("house_number"))
    }
  152. implicit val shorthandSharedTestRegistrationFunction: StringVerbBehaveLikeInvocation
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  153. implicit val shorthandTestRegistrationFunction: StringVerbStringInvocation
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  154. val size: SizeWord
    Definition Classes
    MatcherWords
  155. def someErrors(res0: Boolean, res1: Boolean): Assertion

    But what happens when having one or more errors? They are accumulated in a NonEmptyList wrapped in an Invalid instance.

  156. val sorted: SortedWord
    Definition Classes
    MatcherWords
  157. val startWith: StartWithWord
    Definition Classes
    MatcherWords
  158. final val succeed: Assertion
    Definition Classes
    Assertions
  159. def suiteId: String
    Definition Classes
    Suite
  160. def suiteName: String
    Definition Classes
    Suite
  161. final def synchronized[T0](arg0: => T0): T0
    Definition Classes
    AnyRef
  162. def tags: Map[String, Set[String]]
    Definition Classes
    AnyFlatSpecLike → Suite
  163. def testDataFor(testName: String, theConfigMap: ConfigMap): TestData
    Definition Classes
    AnyFlatSpecLike → Suite
  164. def testNames: Set[String]
    Definition Classes
    AnyFlatSpecLike → Suite
  165. def the[T](implicit arg0: ClassTag[T], pos: Position): ResultOfTheTypeInvocation[T]
    Definition Classes
    Matchers
  166. def theSameElementsAs(xs: GenTraversable[_]): ResultOfTheSameElementsAsApplication
    Definition Classes
    Matchers
  167. def theSameElementsInOrderAs(xs: GenTraversable[_]): ResultOfTheSameElementsInOrderAsApplication
    Definition Classes
    Matchers
  168. val theSameInstanceAs: TheSameInstanceAsPhrase
    Definition Classes
    Matchers
  169. val they: TheyWord
    Attributes
    protected
    Definition Classes
    AnyFlatSpecLike
  170. def thrownBy(fun: => Any): ResultOfThrownByApplication
    Definition Classes
    Matchers
  171. def toString(): String
    Definition Classes
    AnyFlatSpec → AnyRef → Any
  172. val typeCheck: TypeCheckWord
    Definition Classes
    MatcherWords
  173. def typeCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], ev: <:<[B, A]): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  174. implicit def unconstrainedEquality[A, B](implicit equalityOfA: Equality[A]): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
  175. def validatedAsEither(res0: Boolean, res1: Boolean): Assertion

    The withEither method allows you to temporarily turn a Validated instance into an Either instance and apply it to a function.

    withEither

    The withEither method allows you to temporarily turn a Validated instance into an Either instance and apply it to a function.

    import cats.data.Either
    
    def positive(field: String, i: Int): Either[ConfigError, Int] = {
    if (i >= 0) Either.right(i)
    else Either.left(ParseError(field))
    }

    So we can get Either's short-circuiting behaviour when using the Validated type.

  176. val value: ValueWord
    Definition Classes
    Matchers
  177. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.InterruptedException])
  178. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.InterruptedException])
  179. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws(classOf[java.lang.InterruptedException]) @native()
  180. def withClue[T](clue: Any)(fun: => T): T
    Definition Classes
    Assertions
  181. def withFixture(test: NoArgTest): Outcome
    Attributes
    protected
    Definition Classes
    TestSuite
  182. val writable: WritableWord
    Definition Classes
    MatcherWords

Deprecated Value Members

  1. def conversionCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], cnv: (B) => A): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
    Annotations
    @deprecated
    Deprecated

    (Since version 3.1.0) The conversionCheckedConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.

  2. def convertEquivalenceToAToBConversionConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: (A) => B): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
    Annotations
    @deprecated
    Deprecated

    (Since version 3.1.0) The convertEquivalenceToAToBConversionConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.

  3. def convertEquivalenceToBToAConversionConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: (B) => A): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
    Annotations
    @deprecated
    Deprecated

    (Since version 3.1.0) The convertEquivalenceToBToAConversionConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.

  4. def lowPriorityConversionCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], cnv: (A) => B): CanEqual[A, B]
    Definition Classes
    TripleEquals → TripleEqualsSupport
    Annotations
    @deprecated
    Deprecated

    (Since version 3.1.0) The lowPriorityConversionCheckedConstraint method has been deprecated and will be removed in a future version of ScalaTest. It is no longer needed now that the deprecation period of ConversionCheckedTripleEquals has expired. It will not be replaced.

  5. final val styleName: String
    Definition Classes
    AnyFlatSpecLike → Suite
    Annotations
    @deprecated
    Deprecated

    (Since version 3.1.0) The styleName lifecycle method has been deprecated and will be removed in a future version of ScalaTest with no replacement.

Inherited from Section

Inherited from Matchers

Inherited from Explicitly

Inherited from MatcherWords

Inherited from Tolerance

Inherited from AnyFlatSpec

Inherited from AnyFlatSpecLike

Inherited from Documenting

Inherited from Alerting

Inherited from Notifying

Inherited from Informing

Inherited from CanVerb

Inherited from MustVerb

Inherited from ShouldVerb

Inherited from TestRegistration

Inherited from TestSuite

Inherited from Suite

Inherited from Serializable

Inherited from Assertions

Inherited from TripleEquals

Inherited from TripleEqualsSupport

Inherited from AnyRef

Inherited from Any

Ungrouped