Scala案例类私有构造函数但公共应用方法 [英] Scala case class private constructor but public apply method

查看:30
本文介绍了Scala案例类私有构造函数但公共应用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下带有私有构造函数的案例类,并且我无法访问伴随对象中的应用方法.

If I have the following case class with a private constructor and I can not access the apply-method in the companion object.

case class Meter private (m: Int)

val m = Meter(10) // constructor Meter in class Meter cannot be accessed...

有没有办法使用带有私有构造函数的 case 类,但将生成的 apply-method 保留在伴随的 public 中?

Is there a way to use a case class with a private constructor but keep the generated apply-method in the companion public?

我知道这两个选项之间没有区别(在我的例子中):

I am aware that there is no difference (in my example) between the two options:

val m1 = new Meter(10)
val m2 = Meter(10)

但我想禁止第一个选项.

but I want to forbid the first option.

-- 编辑--

令人惊讶的是以下作品(但不是我真正想要的):

Surprisingly the following works (but is not really what i want):

val x = Meter
val m3 = x(10) // m3  : Meter = Meter(10)

推荐答案

这里是使用私有构造函数和公共应用方法的技巧.

Here's the technique to have a private constructor and a public apply method.

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

背景信息private-and-protected-constructor-in-scala

这篇关于Scala案例类私有构造函数但公共应用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆