if
-else
是 Scala 中的表达式。你写的变成:
List[String]() +:
{if (somecondition is satisfied) {" element"; () } else () }+:
{ if (another condition) { " something else "; () } else () }
如您所见,常见的分支类型是Unit
.
整个表达式的类型将是,因为这是andList[Any]
的常见超类型。String
Unit
实现您想要的一些方法:
// #1. Ugly.
def someMethod(obj:MyObj):List[String] = {
val xs = List[String]()
val xs1 = if (somecondition is satisfied) xs :+ " element" else xs
val xs2 = if (another condition) xs1 :+ " something else" else xs1
xs2
}
// #2. Better, but uses mutable builder.
def someMethod(obj:MyObj):List[String] = {
val b = List.newBuilder[String]
if (somecondition is satisfied) b += " element"
if (another condition) b += " something else"
b.result
}
// #3. Best way IMO, but computationally expensive.
def someMethod(obj:MyObj):List[String] = {
List[String]() ++
Option("element").filter(some condition) ++ // for more correct semantics
// use LazyOption from Scalaz.
Option("something else").filter(another condition)
}