Kevin Meredith Kevin Meredith - 1 year ago 107
Scala Question

Using `Option[BigDecimal]` with Anorm?



$cat build.sbt
scalaVersion := "2.11.8"

libraryDependencies += "" % "anorm_2.11" % "2.5.1"


import anorm._

val x: Option[BigDecimal] = Some(42)
val none: Option[BigDecimal] = None

// invoke Oracle function `f`
scala> SQL""" select f(#$x) from dual """.sql.statement
res0: String = " select f(Some(42)) from dual "

scala> SQL""" select f(#$none) from dual """.sql.statement
res1: String = " select f(None) from dual "

I'd like for
to equal:
select f(42) from dual
, and for
to equal
select f(NULL) from dual

How can I modify my
code to fit my desired results?

I imported
, per, however, it did not give my desired result.

Answer Source

Using $ interpolation, just use SQL""" select f($x) from dual """.

You can do it with #$, but you certainly shouldn't (#$ should only be used when you can't do what you want with $: e.g. for interpolating table or column names):

def invokeF(x: Option[BigDecimal]) = {
  val xInSql = x.fold("NULL")(_.toString) // can be inlined to get even less readable
  SQL""" select f(#$xInSql) from dual """
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download