有没有更好的方法来编写这段代码?

时间:2014-07-09 18:02:48

标签: scala

我主要考虑测试可选值并提取这些值。这是代码:

val optEmail: Option[String] = getOptionalEmailParam
val optPassword: Option[String] = getOptionalPasswordParam

if (optEmail.nonEmpty && optPassword.nonEmpty) {
  doSomething(optEmail.get, optPassword.get)
} else {
  doSomethingElse
}

我喜欢

的内容
for (email <- optEmail; password <- optPassword) {
  doSomething(email, password)
} else {
  // Didn't get inside the for loop
  doSomethingElse
}

4 个答案:

答案 0 :(得分:5)

我认为匹配声明在这里看起来很简洁:

val optEmail: Option[String] = getOptionalEmailParam
val optPassword: Option[String] = getOptionalPasswordParam

(optEmail, optPassword) match {
  case (Some(email),Some(password)) => doSomething(email, password)
  case _ => doSomethingElse
}

答案 1 :(得分:3)

只需将for循环变为for/yield(理解),然后使用getOrElse跟进:

val a: Option[String] = Some("a")
val b: Option[String] = Some("b")
val n: Option[String] = None

(for(x <- a; y <- b) yield f"$x $y").getOrElse("else")  // "a b"
(for(x <- n; y <- b) yield f"$x $y").getOrElse("else")  // "else"
(for(x <- a; y <- n) yield f"$x $y").getOrElse("else")  // "else"
(for(x <- n; y <- n) yield f"$x $y").getOrElse("else")  // "else"

单子!

所以:

(for (email <- optEmail; password <- optPassword) yield {
  doSomething(email, password)
}).getOrElse(doSomethingElse)

答案 2 :(得分:1)

类似的东西(它将返回doSomething或doSomethingElse)

(
  for {
    email <- optEmail if email.nonEmpty
    pw  <- optPassword if pw.nonEmpty
  } yield doSomething(email,pw) 
) getOrElse doSomethingElse

答案 3 :(得分:1)

你也可以做这样的事情来自动加密你的代码

   optEmail.fold(doSomethingElse)(
     email => optPassword.fold(doSomethingElse)
       (pw => doSomething(email,pw)))

 (optEmail zip optPassword).
   headOption.fold(doSomethingElse)(p => doSomething(p._1,p._2))