在Scala中将条件转换为Option

时间:2016-03-31 02:43:37

标签: scala

我想做这样的事情。

        intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("http://www.youtube.com/playlist?list=PL4rWuj3mdfAtHqyufMu57C9LK8By9M_sy"));
    String title = getResources().getString(R.string.chooser_title);
    Intent chooser = Intent.createChooser(intent, title);
    spec = tabHost.newTabSpec("Tab3").setIndicator("VIDEOS")
            .setContent(chooser);
    tabHost.addTab(spec);

更短的方式如下。

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

使用Try(x > 0).toOption.map(_ => 123) (用于捕获异常)来检查条件似乎有点不自然。还有其他方法可以实现这个目标吗?

编辑:

Try无法正常工作,因为Try在x为负数时不会抛出异常。

2 个答案:

答案 0 :(得分:4)

Some(x).filter(_ > 0).map(_ => 123)

使用Option,您可以使用filtermap

答案 1 :(得分:1)

方法whenScala 2.13提供了Option,如果Some(a)符合条件,则产生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)