Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 602
opensas Avatar asked Apr 01 '12 21:04

opensas


1 Answers

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 {""})
like image 69
Tomasz Nurkiewicz Avatar answered Oct 01 '22 00:10

Tomasz Nurkiewicz