Multi-file ADTs #21907
Replies: 2 comments 12 replies
-
The use case falls under "prefer composition to inheritance". Delegation to private implementation classes is made trivial by
Instead of "multifile ADT", I think a more generally useful feature would be "multifile compilation unit". That would allow a huge class with its huge companion object to be in two files. (That has been requested previously.) No doubt this could be implemented in a build tool, since the compiler is nominally agnostic about how a compilation unit is sourced. |
Beta Was this translation helpful? Give feedback.
-
I like the idea and here is my proposal to it : Proposal: Cross-File Sealing for Sealed Traits with Explicit Subtype DeclarationMotivation Proposed Solution Example import com.example.MyClass1
import com.example.MyClass2
import com.example.MyClass3
sealed trait MyTrait {
// ... trait definition ...
} applyTo(com.example.MyClass1, com.example.MyClass2, com.example.MyClass3) To improve conciseness, the following syntactic sugar could be used, which is equivalent to the import com.example.MyClass1
import com.example.MyClass2
import com.example.MyClass3
sealed trait MyTrait {
// ... trait definition ...
} (com.example.MyClass1, com.example.MyClass2, com.example.MyClass3) Explanation Benefits Compiler Optimization: Clarity and Maintainability: Semantic Consistency: The use of applyTo aligns with the semantic of the apply method, making the syntax more intuitive. Enforcement of Subtype Restrictions Example // In a separate file:
class UnauthorizedClass extends MyTrait // Should result in a compilation error Potential Considerations Use Cases Next Steps Thank you for your consideration. |
Beta Was this translation helpful? Give feedback.
-
Hi,
Here is a proposal to add the
permits
keyword onsealed
traits and classes to allow the implementation of multi file ADTs:This would work similarly to Java 17: https://docs.oracle.com/en/java/javase/17/language/sealed-classes-and-interfaces.html
We have multiple instances were we dropped the sealed keyword just because the file was too big.
Some other are using a trick with traits: https://github.com/BalmungSan/scala-multifile-adt
Thanks
Beta Was this translation helpful? Give feedback.
All reactions