How can you use Scala to enforce compile-time checks?

Instruction: Discuss techniques in Scala that can be used to enforce compile-time validations.

Context: This question assesses the candidate's familiarity with Scala's compile-time features, such as implicit evidence and macros, to ensure code correctness before runtime.

Updated

Scala can reject programs whose types violate an API contract. The property must be represented in those types; an arbitrary runtime value is not automatically proven valid by adding an implicit parameter.

final case class NonEmpty[A](head: A, tail: List[A])
object NonEmpty {
  def fromList[A](values: List[A]): Option[NonEmpty[A]] =
    values match {
      case head :: tail => Some(NonEmpty(head, tail))
      case Nil => None
    }
}
def first[A](values: NonEmpty[A]): A = values.head

@main def checkedExample(): Unit = {
  assert(first(NonEmpty(7, Nil)) == 7)
  assert(NonEmpty.fromList(List(1, 2)).map(first) == Some(1))
  assert(NonEmpty.fromList(List.empty[Int]).isEmpty)
}

The first API requires a representation containing a head. Passing a plain List[Int] fails to compile. Converting an ordinary list into that representation still performs a runtime check because its length is runtime data. This assumes ordinary non-null values; Scala's default null mode and unsafe casts can bypass normal type constraints.

Subtype bounds and evidence such as A <:< B establish type relationships. Context bounds require capabilities such as an Ordering[A]; neither automatically proves a business predicate about arbitrary input. Type bounds

Scala 3 inline methods, compile-time operations and macros can perform additional checks when the required information is available during compilation. They cannot generally decide facts about an external response that arrives later. Keep runtime validation at input boundaries, and balance sophisticated types against API clarity, compiler diagnostics and maintenance cost. Compile-time operations

Related Questions