Creating immutable data structures, I really like the concept of Scala, where you can enforce object instantiation only via factory method in this way using case class (having a private canonical constructor) and companion object.
final case class Foo private(a: Int)
object Foo {
def apply(left: Int, right: Int) = Foo(left + right)
}
With Java 14, the concept of records have been introduced, providing most of Scala's case class features.
However, making the canonical constructor of records private
seems to be a bit cumbersome... Is there any way to achieve the same behavior with Java's records?
@RequiredArgsConstructor
on anything other than class or enum. – Specie