为什么私有构造函数在 class 的情况下仍然可见?

Why is private constructor still visible in case class?

我想在一个 class 中隐藏构造函数及其字段,并且只使用伴随对象创建实例,但我无法实现。我有 scala 2.13.3,它基于 java 8。这是一个代码示例:

A.scala

package X

object A {
  def apply(x: Int): A = A(Seq(x))
}

case class A private(private val s: Seq[Int])

B.scala

package Y

import X.A

class B {
  val b = A(Seq.empty)
}

虽然我只想让 apply(x:Int) 可见,但此代码编译后私有构造函数也是可见的。我怎样才能更改此代码以按预期工作?

也将方法A.apply(Seq[Int])设为私有

A.scala

package X

object A {
  def apply(x: Int): A = A(Seq(x))
  private def apply(s: Seq[Int]): A = new A(s) // make explicit and private instead of auto-generated and public
}

case class A private(private val s: Seq[Int])

B.scala

package Y

import X.A

class B {
  //val b = A(Seq.empty) // doesn't compile
}

此处 val b = A(Seq.empty) 行产生错误

Error: polymorphic expression cannot be instantiated to expected type;
 found   : [A]Seq[A]
 required: Int

即方法 A.apply(Seq[Int])B 中不可见。