As many people have expressed in the other thread, the cost of writing one extra line for a wrapper function, and one extra line for a unwrapping function is lower than the cost of having to suppress these functions when they are not wanted.
I would love if the apply / unapply would be generated by default for all opaque types. This will cover most of the cases but only if we are allowed to modify their visibility (ie. private
or public
). E.g. sometimes people want to disallow creating invalid instances and want to run some validation first, returning Option
or Either
. In such cases, they could make the default apply
private and create a function acting as a smart constructor.
I personally don’t do this since I believe it conflates validation with the idea of newtypes. This is the reason why I use and endorse the idea of Newtypes + Refined. The former to differentiate similar types (e.g. String
) and the latter to define the validation rules, both at compile time and runtime.
I went through most of the responses in the other thread and I believe some disagree with having a default apply / unapply. If that’s the case, would it be possible to somehow tell Scala we want these wrapping / unwrapping functions to be automatically generated? Maybe a compiler flag? An import?
This would absolutely be possible! I actually proposed it here:
That would be awesome! Has there been any progress on this proposal? I like it, even if it’s just sugar, it greatly improves the user experience.