scala newbie having troubles with Option, what's the equivalent of the ternary operator

StackOverflow https://stackoverflow.com/questions/9968611

  •  28-05-2021
  •  | 
  •  

Question

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...

Was it helpful?

Solution

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 ifs (missing parentheses around if):

"select * from xx" + (if(order.isDefined) {" order by " + order.get} else {""})

OTHER TIPS

...or, if you really want to impress your friends:

order.foldLeft ("") ((_,b)=>"order by  " + b)

(I would still recommend Tomasz's answer, but I think this one is not included in the scala.Option cheat sheet, so i thought I'd mention it)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top