gpt4 book ai didi

scala - 基于 bool 值填充枚举集

转载 作者:行者123 更新时间:2023-12-02 08:40:50 25 4
gpt4 key购买 nike

我有一个集合:为了便于讨论,我们称它为fruitBasket: Set[Fruit]

Fruit 枚举有 ApplePearOrange 等值

我要用以下内容填充 fruitBasket:

  • Apple 如果 bool 值 hasApple 为真
  • Pear 如果 bool 值 hasPear 为真,
  • Orange 如果 bool 值 hasOrange 为真

fruitBasket 将包含 ApplePearOrange 如果所有三个 bool 值都为真,例如

请问在 Scala 中执行此操作的语法最简洁的方法是什么?

现实生活中的用例是 Play 中处理复选框的表单映射。我不喜欢我当前的实现,感觉很笨拙:

var modes = Set[ExchangeMode]()
if (exchangeModeL) modes += LenderHosts
if (exchangeModeD) modes += DropOffToBorrower
if (exchangeModeP) modes += AtPublicPlace
modes

最佳答案

如果您更喜欢推导式和模式匹配元组:

for {
(b, v) <- Set(hasApple->Apple, hasPear->Pear, hasOrange->Orange) if b
} yield v

关于scala - 基于 bool 值填充枚举集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com