Private canonical constructor for record

Viewed 1462

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?

1 Answers

It seems that record cannot fulfill usecases possible in scala. "java" way for doing this is using class with private constructor:

public class Foo private {
    private final Integer a;
    private Foo(Integer a) {
        this.a = a;
    }
    public Foo of(Integer left, Integer right) {
        return new Foo(left + right);
    }
}

Through using opinionated lombook library, you can lower down boilerplate to scala level:

@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class Foo private {
    private final Integer a;

    public Foo of(Integer left, Integer right) {
        return new Foo(left + right);
    }
}
Related