A nonempty list is a list data structure constrained to contain at least one element. Representing it as a head and tail makes the constraint visible in its type. section 12.4.1
Accumulating validation errors
Web-form validation can return several failures at once. Replacing List[String] with NonEmptyList[String] rules out Invalid(Nil), because every invalid result must contain an error. The trade-off is algebraic: NonEmptyList supports associative combination, but cannot provide a Monoid identity value. section 12.4.1 section 12.9
Since combining two nonempty lists always remains nonempty, NonEmptyList has a Semigroup instance. Its Applicative validation combines two Invalid values with combine, while preserving a Valid result when both inputs succeed. section 12.4.1
case class NonEmptyList[+A](head: A, tail: List[A]):
def toList: List[A] = head :: tail
object NonEmptyList:
def apply[A](head: A, tail: A*): NonEmptyList[A] =
NonEmptyList(head, tail.toList)
Inspect the Scala representation: a required head stores the first element, while the tail stores any remaining elements. section 12.4.1
