I'm trying to implement an Argonaut JSON decoder instance that converts JSON strings to instances of my enum QuestionType
. The problem is that if the string isn't a valid, the returned DecodeResult should be an error, and I'm not sure how to do that.
My code currently looks like this:
implicit def QuestionTypeDecodeJson: DecodeJson[QuestionType] = {
DecodeJson(c => for {
typeName <- c.as[String]
questionType = QuestionType.fromString(typeName).get
} yield questionType)
}
QuestionType.fromString(typeName)
returns an Option
. Ideally, instead of using get
, I would like to convert the Option
to a DecodeResult
, with either the contents of the Option, or an error state if it's None
.
I could use the constructor of DecodeResult
, but to be honest the signature of that is quite confusing to me (I'm new to scala). It seems that it requires a CursorHistory
object, and I'm not sure what I'm supposed to pass in there.
DecodeResult object has an 'ok' and a 'fail' method.
implicit def QuestionTypeDecodeJson: DecodeJson[QuestionType] = {
DecodeJson(c => for {
typeName <- c.as[String]
questionType = DecodeResult.ok(QuestionType.fromString(typeName))
} yield questionType)
}