2

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

斯卡拉

package X

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

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

斯卡拉

package Y

import X.A

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

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

4

1 回答 1

5

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

斯卡拉

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])

斯卡拉

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

于 2020-07-16T09:21:41.153 回答