在Scala中替换if-without-else

nul*_*ull 5 functional-programming scala

您通常如何以功能方式在Scala中替换if-without-else?

例如,像这样的命令式典型模式:

var list = List("a", "b", "c")

if (flag) { // flag is boolean variable
    // do something inside if flag is true
    list = "x" :: list
}
// if flag is false, nothing happened
Run Code Online (Sandbox Code Playgroud)

我在想这样使它起作用:

val tempList = List("a", "b", "c")
val list = if (flag) "x" :: tempList else tempList
Run Code Online (Sandbox Code Playgroud)

如果不使用中间变量,是否会有更好的方法?

因此,任何人都可以分享如何在scala中消除if-without-else?

Rex*_*err 4

通常,最好避免临时变量使命名空间变得混乱。所以这样的事情会更好:

val list = {
  val temp = List("a", "b", "c")
  if (flag) "x" :: temp else temp
}
Run Code Online (Sandbox Code Playgroud)

或者

val list = List("a", "b", "c") match {
  case x if flag => "x" :: x
  case x => x
}
Run Code Online (Sandbox Code Playgroud)

如果您发现自己经常这样做并且性能不是一个大问题,那么定义一个扩展方法可能会很方便。我的个人图书馆里有一个看起来像这样的:

implicit class AnythingCanPickFn[A](private val underlying: A) extends AnyVal {
  /** Transforms self according to `f` for those values where `p` is true. */
  @inline def pickFn(p: A => Boolean)(f: A => A) =
    if (p(underlying)) f(underlying) else underlying
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用这个:

List("a", "b", "c").pickFn(_ => flag){ "x" :: _ }
Run Code Online (Sandbox Code Playgroud)

  • 在“match”的情况下,不应该是“x” :: x吗? (3认同)