I have two case classes A and B. I need to create Json object conditionally
Json.toJson(if (cond) A else B)
if (cond) Json.toJson(A) else Json.toJson(B)
Statement 1 does not compile but statement 2 does. What is the reason behind this?
The signature of toJson(...)
is:
toJson[T](o: T)(implicit tjs: Writes[T]): JsValue
That means that there must be an implicit Writes
in scope for the type of argument T
.
Now, the type of the expression if (cond) A else B
is the common super type of the respective types of values A and B.
For types that don't explicitly inherit from the same base class the common super type will be Scala's Any
. There is no implicit Writes
for Any
(because what is the JSON representation of anything?) so you'll get an "implicit not found" error at compile time.
On the other hand, each branch of the conditional in statement 2 evaluates to JsValue
, so that is the value of the expression.