scala - 有没有办法在 Scala 中动态添加约束?
问题描述
我正在尝试模拟一家接受客户在线订单的面包店。
为此,我有 4 个课程:
- 顾客:
- 年龄
- 钱
- 性别
- 命令:
- 天
- 小时
- 顾客
- 面包店:
- 姓名
- 面包:
- 尺寸
- 颜色
- 品尝
- 姓名
我希望能够在有一些限制的情况下向 Baakery 添加订单。例如:
- “仅当客户年满 18 岁时才允许下单”
- “如果顾客年龄大于 18 岁且小于 30 岁,只允许订购白面包”
- “如果顾客年龄超过 65 岁,只有在口味‘好’的情况下才允许下单”
当然,这些可以写为 baker.addOrder(o: Order) 函数中的 if-else 构造,但我的问题是:有没有办法动态添加这些。因此,例如:
- baker.addConstraint(customer.age, ">18")
- baker.addAndConstraint(customer.age, "">18", customer.age, "<30", bread.color == "white")
有没有办法做到这一点,或者有更优雅的解决方案?
解决方案
您可以将这些约束定义为函数,并根据配置将它们收集到一个活动约束列表中,以提供给您的面包店。
例如
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))
推荐阅读
- terraform - Terraform For 循环从地图生成 JSON
- android - Android Picasso 将之前加载的图片设置为占位符
- elasticsearch - Elasticsearch 服务器超时
- angular - 在两个日期之间查询在 MongoDB 中返回不正确的结果?
- python - 如何从 python 代码写入 .env 文件
- django - 表格(前缀=)和比赛条件
- c# - 如何处理多个对象共享的数据
- spring-boot - 如何使用 mockito 模拟方法?
- reactjs - 替换 React 组件 onClick
- python - 致命错误 LNK1181:安装 matplotlib==3.0.3 时无法打开输入文件“png.lib”