//> using scala 3.9.0
import scala.deriving.Mirror
final case class Email private (value: String)
object Email {
def from(value: String): Email = new Email(value.toLowerCase)
}
@main def repro(): Unit = {
// Email("X@Y") // does not compile: apply is private (E050)
// new Email("X@Y") // does not compile: constructor is private
val email = summon[Mirror.ProductOf[Email]].fromProduct(Tuple1("X@Y"))
println(email) // Email(X@Y): built outside the companion, bypassing Email.from
}
When we want to create a private constructor:
we want to disallow extending the class, so we’re making it final and the constructor private
it prevents the creation of copy, that could bypass the smart constructor
it also prevents users from being able to call new
the only way we should be able to create an instance, is via factory methods provided in the companion object
I checked that fromProduct inherits the access modifier from the constructor (Email.fromProduct is not visible outside), but Mirrors simply cast the companion object to a Mirror, and we’re bypassing the access modifier in runtime.
That means that every type-class derivation based on Mirrors, bypasses the smart constructors, and that kind-of undermines the whole premise in my humble opinion.
Is it a bug, or an intended behavior that warrants some Pre-SIP?
Its part of the design of Mirror that fromProduct calls the constructor even if private, which is why it refuses to create a mirror for a Scala 2 case class with a private constructor as the mirror is an anonymous class in that case instead of the companion object.
Of course we could introduce some API to redirect mirror’s factory function (or opt out of compiler provided mirror)
What was the reasoning behind the decision it should ignore access control modifier? Because it’s compile-time reflection? The API to redirect mirror’s factory function sounds like a very good idea but what if there are many smart constructors (overloaded or just differently named)?
I checked that Shapeless in the same situation (when we use -Xsource-features:case-apply-copy-access and -Xsource:3 for Scala 3 compatibility) would fail to provide a Generic. So, the idea there was, that if you would not be able to safely instantiate a constructor somewhere, you should not be able to perform derivation there.
By that logic, since Mirrors are intended for derivation, they should not allow summoning Mirror.ProductOf for case classes with private constructors outside their companion, even though they are still case classes - because they are not legally instantiable case classes outside the companion.
A perspective of an application developer. I would never wish for my smart constructor logic to be circumvented. Ideally, I would like both derivation and smart constructors to work. Still, forced to pick only one, I would go for correctness (smart constructors) at the expense of derivation.
I have tried again and forgive me i misremembered.
What i said about the constructor is the default implementation the compiler will generate,
What you can do now is define fromProduct yourself in the companion object and the mirror will magically be defined correctly - the compiler checks first for existing definitions.
So we could enhance the default “is class X generic” check to only allow to summon a Mirror for a class with a private constructor without a pre-existing compatible fromProduct definition inside the classes own scope - then if it finds such a definition its up to you to be correct.
Of course - if your smart constructor does not return the class directly but wraps in some result, then i guess you have to make fromProduct throw, but it should already be understood as an “unsafe method”. And for most extreme If you have no way to do it except by using IO monad then i think the design is just incompatible with mirror
I meant only allow to summon a mirror for a class with a private constructor (for a class where the companion does not define a pre-existing fromProduct) if the summon occurs in the classes own scope.
and if the compiler is generating fromProduct itself, then allowing naked access to that mirror from outside the scope would have to be provided via an explicit public definition, so equivalent to providing a forwarder to the private method
I imagine that if users received warnings, that their derivation used fromProduct outside of a companion, they would opt-out of that derivation, at least in that place.
The majority of smart constructors that I saw (and majority of recommendations for Scala) were Either[String, Type] factories, conforming to parse-don’t-validate and exceptions-are-not-business-errors.
Throwing from fromProduct looks live a javaism, at this point I can just throw from the constructor with an assert, since the type system is no longer helping me to avoid mistakes.
IMHO, the only way it works as expected is if summoning of a Mirror.ProductOf fails if the constructor is private. If that needs some transition period a warning can be added (and a flag that brings the no-summon behavior), so that people would at least be aware that e.g. by decoding JSON they can get data that would not pass validation.
From this i am only seeing that Mirror should be rejected for any classes that follow the smart constructor pattern? so derivation library’s should just throw it out and go back to macros? or you would accept some way to redirect fromProduct?
Or perhaps some factory functions and builtin types for building Mirrors that have the right types in their public API but you control the implementation
Yes, I think this is the way, with (maybe?) some common denominator type, e.g., Either[String, T].
Easier said than done, of course. A library for deriving JSON decoders would no longer be able to claim, “I will decode any string to a valid Email, no matter what the smart constructor does”. How to express that in the Mirror API?
Currently we have a mechanism with no opt-out that skips smart constructors in every codebase that uses type class derivation - since majority of libraries use Mirrors for derivation, and people are not aware that of this gap - neither library maintainers, nor library users.
Whether that could be re-added as opt-in, manual fromProduct that explicitly throws, or by making Mirrors smart-constructor-aware is another question. I do not intend to use Mirrors myself for anything serious, so I am not concerned with such changes.
But as it is right now, if I am using smart constructors to model my domain (with private constructor in a case class as intended), I can believe that my code is correct by design, while in reality the only thing guarding me from a bug might be existence of some random unit test, because someone else implemented a library on top of Mirrors and I cannot do anything about it other than forking the derivation.
The treatment of the private constructor of a case class is something that we wanted to fix from Scala 2.13 (which required this funny sealed abstract case class pattern, and we made sure to hide apply, new, copy and e.g. fromProduct for the outside world) and everyone reading about changes from 2.13 was convinced that we finally fixed it, but discovery of this behavior kind or undermines that: if I want to use smart constructors do model domain, I would basically have to ban Mirror-based libraries from my codebase. (Or write some scalafix rule/tasty inspector to do the compiler’s job).
so is another problem that Mirror’s “generic class” criterion guarantees that basically all the component fields need no pre-validation? I guess the generic way around this would be that the fields should be of a type that has its own smart constructor, so not raw Int but some class/opaque type that defines its own decoder that performs the validation. (because the design pattern for Decoder[X] with m.MirroredElemTypes =:= (Y,Z) is to summonAll[(Decoder[Y], Decoder[Z])])
so the only opt-out of mirror being generated by compiler currently is to not be a case class - or add a secondary parameter list case class Email private (addr: String)(). Alternatively yeah that Email class can define its own mirror in the companion. The validation step is then in your generic decoder to wrap fromProduct with a try/catch.
to grow the API, we can also add the option for decoders to perform a dynamic subtype check for a new ValidatedProduct trait? Or we can add a stackless exception that extends IllegalArgumentException to the scala.deriving package to make it cheap to throw.
Please, no runtime exceptions, at least without an explicit user opt-in (e.g., -Xsource-features:mirror-derivation-can-throw). Much of the value of Scala is that edge conditions are expressed within signatures and not hidden in implementation/documentation. Having to choose between a runtime exception and the inability to handle smart constructors in derivation, I go for the latter every time.
Newtypes work when you can validate things per-field.
They do not help if you want to have parse-don’t-validate expression e.g. relationships between fields, excluding “forbidden” combination of values that would be impractical to express with a single enum, etc. To use newtypes in such case, one would have to make a newtype out of a whole case class. Or use assertions and runtime errors.
Which is basically against anything already existing and based on:
design patterns recognized in multiple existing languages (smart constructors)
general DDD practices (domain model should be trustworthy, exception is not a business error and vice versa)
FP approach to correctness (“parse, don’t validate”, “make illegal states unrepresentable”, “make errors explicit”)
functional approach to domain design (see: Scott Wlaschin’s book in F# - there even if data object has no behavior, it is still parsed with an Either-like result type)
One might not sign up to these, but we cannot at the same time claim that Scala invest in compile-time checks and type-safety and use reflection to side-step a type’s built-in validation out of nowhere.
Please note the long-term, high-impact consequences of the (very unfortunate) runtime exception proposal. A third-party library (e.g., circe) could opt to use Mirrors. Many applications would define Email-like types with smart constructors. Everything would compile, and people ship the apps. But they would be getting runtime exceptions for incorrect input.
That developer experience is very unlike Scala. It is more like old-style Java. People in new programming languages pick up sum types (Rust’s Result) to model error conditions. Scala APIs should not regress to the old-style Java world. What would be the advantage of using Circe in Scala over Jackson reflection in Java?
But Mirrors are already there, and they already compile (even when they shouldn’t, the point of this thread)
We should at the very least do this:
And then we can see about additions that allow “partial fromProduct” (either through partial functions, returning Left, raising or something else)
I believe this latter step should be discussed in a different thread
(Personally, I am getting confused as to who is opposing to what)
The current state, as I don’t want anything (Mirrors included) to be able to circumvent my smart constructors. I would rather see a compilation failure and have to redo my design.
Relying on runtime exceptions anywhere, as I want the ability to predict my program’s behavior from the signatures alone.
I agree that splitting this thread into two discussions would be beneficial. First, let’s address the immediate problem that @MateuszKubuszok described. Second (separate thread), let’s try to come up with a solution to use Mirror derivation for types with smart constructors.