How do you usually use to replace if-without-else in Scala in functional way?
For example, like this typical pattern in imperative style:
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
I'm thinking like this to make it functional:
val tempList = List("a", "b", "c")
val list = if (flag) "x" :: tempList else tempList
Could there be a better way without using intermediary variable?
So anyone can share how do you eliminate if-without-else in scala?
ifwithout anelse- you always need to get some value back. You only might not need to declare it explicitly, when you use a function that provides a default value.