Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play 2.3 writing options with Json.obj and getOrElse

From the activator console this works:

scala> import play.api.libs.json._
import play.api.libs.json._

scala> val testVal = Some("foo")
testVal: Some[String] = Some(foo)

scala> Json.obj("myJson" -> testVal)
res0: play.api.libs.json.JsObject = {"myJson":"foo"}

This also works:

scala> Json.obj("myJson" -> testVal.get)
res3: play.api.libs.json.JsObject = {"myJson":"foo"}

This fails:

scala> Json.obj("myJson" -> testVal.getOrElse(""))
 <console>:12: error: type mismatch;
  found   : Object
  required: play.api.libs.json.Json.JsValueWrapper
          Json.obj("myJson" -> testVal.getOrElse(""))

But this works:

scala> val testVal2 = testVal.getOrElse("")
testVal2: String = foo

scala> Json.obj("myJson" -> testVal2)
res2: play.api.libs.json.JsObject = {"myJson":"foo"}

Why does the compiler reject my third example? testVal.getOrElse("") evaluates to a String so why does the compiler think it is Object in the third example above?

like image 420
imagio Avatar asked Dec 11 '14 17:12

imagio


1 Answers

You can also help a bit getOrElse method to directly define its return type

Json.obj("myJson" -> testVal.getOrElse[String](""))
like image 193
Leszek Gruchała Avatar answered Oct 01 '22 19:10

Leszek Gruchała