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

Support for private constructors (via private Coercible instances) #70

Open
mrdziuban opened this issue Jan 21, 2022 · 0 comments
Open

Comments

@mrdziuban
Copy link

The Coercible instances currently generated by the @newtype macro are always publicly available in implicit scope. I think this makes sense when defining a newtype as a case class since a standard apply method will be generated, but when defining one as a class with a custom apply method, it allows external code to bypass any validation logic in that method. For example

// types.scala
package object types {
  @newtype class PositiveInt(i: Int)
  object PositiveInt {
    def apply(i: Int): Option[PositiveInt] = if (i > 0) Some(i.coerce[PositiveInt]) else None
  }
}

// test.scala -- this compiles but ideally it wouldn't
-1.coerce[types.PositiveInt]

Would it be possible to make the Coercible instances for a class only visible in implicit scope in the companion object? Or if that seems like too broad of a change, perhaps the logic could only apply when the class constructor is explicitly marked as private, e.g. @newtype class PositiveInt private (i: Int)?

Thank you for all your work on this library!

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

No branches or pull requests

1 participant