xan*_*xan 2 scala access-modifiers private-constructor case-class companion-object
我想将构造函数及其字段隐藏在一个类中,并且只使用伴随对象创建实例,但我无法实现。我有 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])
Run Code Online (Sandbox Code Playgroud)
甜菜
package Y
import X.A
class B {
val b = A(Seq.empty)
}
Run Code Online (Sandbox Code Playgroud)
虽然我只想让apply(x:Int)这段代码可见,但编译后的私有构造函数也是可见的。如何更改此代码以按预期工作?
也将方法设为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])
Run Code Online (Sandbox Code Playgroud)
甜菜
package Y
import X.A
class B {
//val b = A(Seq.empty) // doesn't compile
}
Run Code Online (Sandbox Code Playgroud)
这里的行val b = A(Seq.empty)产生错误
Error: polymorphic expression cannot be instantiated to expected type;
found : [A]Seq[A]
required: Int
Run Code Online (Sandbox Code Playgroud)
即该方法A.apply(Seq[Int])是不可见的B。
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |