gpt4 book ai didi

scala - 在 Scala 中将条件转换为选项

转载 作者:行者123 更新时间:2023-12-05 08:14:02 26 4
gpt4 key购买 nike

我想做这样的事情。

if (x > 0) {
Some(123)
} else {
None
}

更短的方法如下。

Try(x > 0).toOption.map(_ => 123)

使用 Try(旨在捕获异常)来检查条件对我来说似乎有点不自然。还有其他方法可以实现吗?

编辑:

Try 不起作用,因为当 x 为负时 x > 0 不会抛出异常。

最佳答案

启动 Scala 2.13Option 随方法提供 when ,如果 a 匹配条件,则生成 Some(a),否则生成 None:

// val x = 45
Option.when(x > 0)(x)
// Option[Int] = Some(45)

// val x = -6
Option.when(x > 0)(x)
// Option[Int] = None

// val x = 45
Option.when(x > 0)(123)
// Option[Int] = Some(123)

关于scala - 在 Scala 中将条件转换为选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323228/

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