Design a DSL in Scala for a given domain.

Instruction: Outline the approach and code for creating a domain-specific language (DSL) in Scala for a simple application domain of your choice.

Context: Evaluates the candidate's ability to apply Scala's language features to design a readable and expressive domain-specific language, showcasing creativity and understanding of DSLs.

Updated

Use an immutable task model, explicit defaults and a small set of operations. This Scala 3 internal DSL constructs and queries task values; persistence and task execution are separate concerns.

enum Priority { case High, Medium, Low }
final case class Task(
    name: String,
    priority: Priority = Priority.Low,
    tags: Set[String] = Set.empty
) {
  require(name != null && name.trim.nonEmpty, "Task name is required")
  require(priority != null, "Priority is required")
  require(tags != null && tags.forall(t => t != null && t.trim.nonEmpty),
    "Tags must be nonblank")
}
object TaskDSL {
  def task(name: String): Task = Task(name)
  extension (t: Task) {
    def withPriority(p: Priority): Task = t.copy(priority = p)
    def withTags(values: String*): Task = t.copy(tags = values.toSet)
  }
  def tagged(tasks: List[Task], tag: String): List[Task] =
    tasks.filter(_.tags.contains(tag))
}
@main def taskDslExample(): Unit = {
  import TaskDSL.*
  val draft = task("Write report")
  val urgent = draft.withPriority(Priority.High).withTags("scala", "review")
  assert(draft.priority == Priority.Low && draft.tags.isEmpty)
  assert(tagged(List(draft, urgent), "review") == List(urgent))
}

withTags replaces the tag set and removes duplicates; matching is exact and case-sensitive. copy preserves the original task and reruns constructor validation. This example rejects invalid input with IllegalArgumentException; an interactive form or parser could instead return a structured Either error before constructing a task.

The model uses a single enum for all priorities and regular extension methods rather than ambiguous conversions or undefined aliases. Domain rules remain in the model so callers cannot bypass them by avoiding the DSL syntax. Scala 3 extension methods

Add stable task IDs, storage and state transitions only if the domain requires them. Such additions need their own validation and concurrency rules. Readable construction syntax alone does not implement scheduling, durable storage or authorization.

Related Questions