I'm writing a function to get an entry from a JSONObject
. Since it is JSON the entry by the input name may or may not exist and so the function return an Option
which will be None
when the Try
fails or if the value is NULL
on success. The function fails to compile and errors about incorrect return type.
def tryGet[T](jsonObject: JSONObject, name: String): Option[T] = {
Try(jsonObject.get(name))
.map(x => if(JSONObject.NULL.equals(x)) None else x.asInstanceOf[T])
.toOption
}
Error:
Expression of type Option[Any] doesn't conform to expected type Option[T]
Can someone tell me what I'm doing wrong here? Also, is this the idiomatic way to approach the problem?
Update:
Changing to the below works
def tryGet[T](jsonObject: JSONObject, name: String): Option[T] = {
Try(jsonObject.get(name))
.filter(!JSONObject.NULL.equals(_))
.map(_.asInstanceOf[T])
.toOption
}