Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CaseClass.constructEither #118

Closed
fommil opened this issue Jul 31, 2018 · 1 comment · Fixed by #120
Closed

CaseClass.constructEither #118

fommil opened this issue Jul 31, 2018 · 1 comment · Fixed by #120

Comments

@fommil
Copy link
Contributor

fommil commented Jul 31, 2018

The current implementation of CaseClass.construct means that typeclasses that stop at Functor can be implemented (e.g. Default), but typeclasses with a MonadError (e.g. a JSON decoder) cannot.

The workaround is to use locally scoped exceptions, e.g.:

  private case class Fail(msg: String) extends Exception with NoStackTrace

  def combine[A](ctx: CaseClass[JsDecoder, A]): JsDecoder[A] = {
    case obj @ JsObject(_) =>
      try {
        val success = ctx.construct { p =>
          val value = obj.get(p.label).getOrElse(JsNull)
          p.typeclass.fromJson(value) match {
            case \/-(got)  => got
            case -\/(fail) => throw new Fail(fail) // scalafix:ok
          }
        }
        \/-(success)
      } catch {
        case Fail(msg) => -\/(msg)
      }
    case other => JsDecoder.fail("JsObject", other)
  }

it would be better if you allowed a traversal, even just for Either, allowing

  private case class Fail(msg: String) extends Exception with NoStackTrace

  def combine[A](ctx: CaseClass[JsDecoder, A]): JsDecoder[A] = {
    case obj @ JsObject(_) =>
        ctx.constructEither { p =>
          val value = obj.get(p.label).getOrElse(JsNull)
          p.typeclass.fromJson(value)
        }
    case other => JsDecoder.fail("JsObject", other)
  }

If you produced the boilerplate that called .flatMap then users could even use their own data types, not just Either.

@fommil
Copy link
Contributor Author

fommil commented Jul 31, 2018

another usecase:

import magnolia._
import org.scalacheck._

import scalaz._, Scalaz._
import scalaz.scalacheck.ScalaCheckBinding._

object ScalacheckMagnolia {
  type Typeclass[A] = Arbitrary[A]

  def combine[A](ctx: CaseClass[Arbitrary, A]): Arbitrary[A] = Arbitrary {
    ctx.parameters.toList.traverse(p => Gen.lzy(p.typeclass)).map { ps =>
      ctx.rawConstruct(ps)
    }
  }

  def dispatch[A](ctx: SealedTrait[Arbitrary, A]): Arbitrary[A] = Arbitrary {
    Gen.frequency(ctx.subtypes.map(s => 1 -> (Gen.lzy(s.typeclass.arbitrary))): _*)
  }

  implicit def gen[A]: Arbitrary[A] = macro Magnolia.gen[A]

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant