scala-newtype icon indicating copy to clipboard operation
scala-newtype copied to clipboard

Evaluate the possibility of not generating Coercible instances

Open barambani opened this issue 7 years ago • 2 comments

There are use cases when the generation of the Coercible instances is not required. One example might be when using @newtype annotation in the internal implementation of a library without bringing a runtime dependency on the Coercible type to the users of the latter. A possible way could be to add another flag like the ones in here to drive select this behaviour. Something like coercible: Boolean = true. Thanks.

barambani avatar Aug 20 '18 21:08 barambani

The compelling use case for this is for users who do not wish to have a runtime dependency on newtype (e.g. for a library).

There are some risks though as this means changing the encoding for newtype. Ideally, we could adjust it so that the interface will stay the same. This means that I don't think it would be a good idea to force users to supply coercible = true to get Coercible instances. We could do coercible = false instead, but I want to limit the amount of options that @newtype takes for simplicity.

I have experimented a bit with making newtype a scalac plugin instead, that may be a step in the right direction.

Also, I had started another experiment a while back to see if we could abstract Coercible out of newtype into its own coercible library. At this point though, since we're introducing NewTypeArray, these could just be provided as part of the newtype library, something that would be optional in conjunction with the newtype plugin.

One big hack that might just work is to have the newtype plugin generate a type in the companion that signals to Coercible/NewTypeArray that it is indeed Coercible.

@newtype case class Foo(x: Int)
// generates
type Foo = Foo.Type
object Foo {
  ...
  type __GenerateCoercible
  type __GenerateNewTypeArray
  val __reprClass = scala.Predef.classOf[Int]
  val __reprClassTag = scala.reflect.classTag[Int]
}

Then we'd use an instance materializer macro in Coercible and NewTypeArray that checks for a __Generate type in the companion.

This is mostly a stream of consciousness. There's also an effort to bring newtypes into cats, so whatever we do we need to coordinate to ensure things work well for everyone involved.

carymrobbins avatar Aug 21 '18 17:08 carymrobbins

Just to clarify, in my suggestion I meant that as default, so the user would need to specify if she doesn't like for the Coercible to be generated. Same as you mention. Could you elaborate more about the plugin ? How could it help in selecting the desired expansion ? Thanks a lot for looking into this.

barambani avatar Aug 22 '18 00:08 barambani