首页 > 解决方案 > 有没有办法在 Scala 中动态添加约束?

问题描述

我正在尝试模拟一家接受客户在线订单的面包店。

为此,我有 4 个课程:

我希望能够在有一些限制的情况下向 Baakery 添加订单。例如:

当然,这些可以写为 baker.addOrder(o: Order) 函数中的 if-else 构造,但我的问题是:有没有办法动态添加这些。因此,例如:

有没有办法做到这一点,或者有更优雅的解决方案?

标签: scalaoop

解决方案


您可以将这些约束定义为函数,并根据配置将它们收集到一个活动约束列表中,以提供给您的面包店。

例如


case class Customer(age: Int)
case class Order(customer: Customer, breadType: String)


// define a constraint as a function that checks an Order 
// and returns an error message if it is rejected
type OrderConstraint =  Order => Option[String]

// some example constraints
val ofAge: OrderConstraint = order => 
  if (order.customer.age < 18) Some("Too young to order") else None

val whiteBreadOnly: OrderConstraint = order => 
  if (order.breadType != "white") Some("Only white bread available now") else None

// these can now be collected according to runtime conditions
val tuesday = true
val constraints =  if (tuesday) Seq( whiteBreadOnly, ofAge) else Seq( ofAge )

val anOrder = Order(Customer(12), "wholegrain")

// and checked to produce a list of errors
// (empty means the order was okay )
constraints.flatMap(_.apply(anOrder))


推荐阅读