Skip to content

Commit 3147d5f

Browse files
authored
Remove unnecessary error generation when JsUndefined.asOpt is used (#1112)
* Removed unnecessary error generation in the JsUndefined class when the asOpt function was used * Added test for JsUndefined.asOpt function * Formatting
1 parent 5d4a3e3 commit 3147d5f

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

play-json/shared/src/main/scala/play/api/libs/json/JsLookup.scala

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,10 @@ case class JsDefined(value: JsValue) extends AnyVal with JsLookupResult
195195
* Represent a missing Json value.
196196
*/
197197
final class JsUndefined(err: => String) extends JsLookupResult {
198-
def error = err
199-
def validationError = JsonValidationError(error)
200-
override def toString = s"JsUndefined($err)"
198+
def error = err
199+
def validationError = JsonValidationError(error)
200+
override def toString = s"JsUndefined($err)"
201+
override def asOpt[T](implicit fjs: Reads[T]): Option[T] = None
201202
}
202203

203204
object JsUndefined {
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
* Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>
3+
*/
4+
5+
package play.api.libs.json
6+
7+
import play.api.libs.json.Json._
8+
9+
import org.scalatest.matchers.must.Matchers
10+
import org.scalatest.wordspec.AnyWordSpec
11+
12+
class JsLookupSpec extends AnyWordSpec with Matchers {
13+
"JsLookupResult" should {
14+
val obj = Json.obj(
15+
"field" -> 123
16+
)
17+
val result = obj \ "missingField"
18+
19+
"return JsUndefined when a key is missing" in {
20+
result mustBe a[JsUndefined]
21+
}
22+
23+
"return None when calling asOpt on JsUndefined" in {
24+
result.asOpt[Int].mustEqual(None)
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)