dgrandes
dgrandes

Reputation: 1207

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]?

Upvotes: 1

Views: 1406

Answers (2)

Alois Cochard
Alois Cochard

Reputation: 9862

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))

Upvotes: 10

Kim Stebel
Kim Stebel

Reputation: 42037

I think you just got the syntax for the method definition wrong. The way you wrote it you are calling Option.apply on the result of the try/catch block. I think you meant to write this:

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

Upvotes: 2

Related Questions