Eri*_*rik 33 scala apply private-constructor case-class
如果我有以下具有私有构造函数的case类,并且我无法访问companion对象中的apply-method.
case class Meter private (m: Int)
val m = Meter(10) // constructor Meter in class Meter cannot be accessed...
Run Code Online (Sandbox Code Playgroud)
有没有办法将case类与私有构造函数一起使用,但是在公开的伴随中保留生成的apply-method?
我知道两个选项之间没有区别(在我的例子中):
val m1 = new Meter(10)
val m2 = Meter(10)
Run Code Online (Sandbox Code Playgroud)
但我想禁止第一种选择.
- 编辑 -
令人惊讶的是以下工作(但实际上并不是我想要的):
val x = Meter
val m3 = x(10) // m3 : Meter = Meter(10)
Run Code Online (Sandbox Code Playgroud)
Far*_*mor 42
这是使用私有构造函数和公共应用方法的技术.
trait Meter {
def m: Int
}
object Meter {
def apply(m: Int): Meter = { MeterImpl(m) }
private case class MeterImpl(m: Int) extends Meter { println(m) }
}
object Application extends App {
val m1 = new Meter(10) // Forbidden
val m2 = Meter(10)
}
Run Code Online (Sandbox Code Playgroud)
背景信息private-and-protected-constructor-in-scala
看来所请求的行为(私有构造函数但公共.apply
)可能是 Scala 2.12 实现这些的方式。
我从相反的角度来看这个问题 - 希望私有案例类构造函数也阻止该.apply
方法。原因在这里: https: //github.com/akauppi/case-class-gym
有趣的是,用例有何不同。
归档时间: |
|
查看次数: |
17695 次 |
最近记录: |