Scala is a newbie having problems with the option, which is equivalent to the ternary operator

I 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 for the method, and if this parameter (in this case the order) is not passed, just skip it

What will be the most idiomatic way to accomplish what I'm trying to do?

- change -

I think I was too hasty to ask

I found this way

val orderBy = order.map( " order by " + _ ).getOrElse("")

Is this the right thing to do?

I thought the card was for other purposes ...

+5
source share
2 answers

First of all, you are not using Option[T]idiomatically, try the following:

"select * from xx" + order.map(" order by " + _).getOrElse("")

:

"select * from xx" + (order map {" order by " + _} getOrElse "")

:

"select * from xx" + order match {
  case Some(o) => " order by " + o
  case None => ""
}

scala.Option Cheat Sheet. if ( if):

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

... , :

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

( - Tomasz , , scala. , , )

0

All Articles