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

Change to override Prism behaviour for Option #171

Merged
merged 2 commits into from
Mar 26, 2020
Merged

Conversation

vlovgr
Copy link
Contributor

@vlovgr vlovgr commented Mar 20, 2020

The following example fails with a ClassCastException on v1.0.1.

import $ivy.`com.github.fd4s::vulcan:1.0.1`
import cats.implicits._
import vulcan.Codec

sealed trait FirstOrSecond

final case class First(value: Int) extends FirstOrSecond
object First {
  implicit val codec: Codec[First] =
    Codec[Int].imap(apply)(_.value)
}

final case class Second(value: String) extends FirstOrSecond
object Second {
  implicit val codec: Codec[Second] =
    Codec[String].imap(apply)(_.value)
}

val codec = 
  Codec.union[Option[FirstOrSecond]] { alt =>
    alt[None.type] |+| alt[Some[First]] |+| alt[Some[Second]]
  }
// codec: Codec[Option[FirstOrSecond]] = Codec([ "null", "int", "string" ])

codec.encode(Some(First(123)))

This is because the Prism instance for Option is derived using ClassTag, which (due to type erasure) considers Some[A] <: Option[S], regardless of A. This pull request solves the issue by creating explicit behaviour for Option. It does however not solve the issue more generally, and other parametric types still suffer from this issue.

@vlovgr vlovgr merged commit f1f1fba into master Mar 26, 2020
@vlovgr vlovgr deleted the override-option-prism branch March 26, 2020 19:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant