scalaplayframework-2.0

Returning None instead of Option in Scala gives Compilation Error


This is a simple question that I cant just figure out:

The following code gives the following compilation error:

def parseJson(q: String) = Option[JsValue]{
    try{
            Json.parse(q)
    }catch{
        case e: com.codahale.jerkson.ParsingException => None
    }
}

Error

[error]  found   : None.type (with underlying type object None)
[error]  required: play.api.libs.json.JsValue
[error]             case e: com.codahale.jerkson.ParsingException => None

Why cant I return None considering my response type is Option[JsValue]?


Solution

  • You actually want to put Json.parse(q) into Some() and not wrapping the whole code in an Option[JsValue], but using it as signature:

    def parseJson(q: String): Option[JsValue] = {
        try{
           Some(Json.parse(q))
        }catch{
           case e: com.codahale.jerkson.ParsingException => None
        }
    }
    

    But anyway, you should prefer using scala.util.control.Exception:

     import scala.util.control.Exception._
     catching(classOf[com.codahale.jerkson.ParsingException]).opt(Json.parse(q))