Scala:将if转换为case

时间:2013-09-01 00:12:30

标签: scala

我有以下代码段我还在学习Scala并且没有真正使用案例内容:但是我想将if语句转换为更多scala方式:

... 
.flatMap { 
case(title, subtitle, c, d, e, f, g, h) =>
  val tiitleSubTitle = (title + " " + subtitle).split("\\s").toSet.toList
  tiitleSubTitle.map(term => (
    if (a contains term)
    {
      Some(query, term, List(item_id).mkString(","))
    } else {
        None
    }))
}

2 个答案:

答案 0 :(得分:1)

很难说没有描述你想要完成的事情,但也许你想要的东西是:

Seq(title, subtitle)
  .flatMap(_ split "\\s")
  .filter(a contains _)
  .map((query, _, item_id)

直接回答你的问题:你可以替换

{ term => 
  if (a contains term) Some(query, term, item_id)
  else None
}

{
  case term if a contains term => Some(query, term, item_id)
  case _ => None
}

答案 1 :(得分:1)

您可以替换if语句

if (a contains term)
{
    Some(query, term, List(item_id).mkString(","))
} else {
    None
}

使用:

a contains term match {
    case true => Some(query, term, List(item_id).mkString(","))
    case false => None
}