I've already read that the if statement in scala always returns an expression
So I'm trying to do the following (pseudo code)
sql = "select * from xx" + iif(order.isDefined, "order by " order.get, "")
I'm trying with
val sql: String = "select * from xx" + if (order.isDefined) {" order by " + order.get} else {""}
But I get this error:
illegal start of simple expression
order is an Option[String]
I just want to have an optional parameter to a method, and if that parameter (in this case order) is not passed then just skip it
what would be the most idiomatic way to achieve what I'm trying to do?
-- edit --
I guess I hurried up too much to ask
I found this way,
val orderBy = order.map( " order by " + _ ).getOrElse("")
Is this the right way to do it?
I thought map was meant for other purposes...
First of all you are not using Option[T]
idiomatically, try this:
"select * from xx" + order.map(" order by " + _).getOrElse("")
or with different syntax:
"select * from xx" + (order map {" order by " + _} getOrElse "")
Which is roughly equivalent to:
"select * from xx" + order match {
case Some(o) => " order by " + o
case None => ""
}
Have a look at scala.Option
Cheat Sheet. But if you really want to go the ugly way of if
s (missing parentheses around if
):
"select * from xx" + (if(order.isDefined) {" order by " + order.get} else {""})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With