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

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

问题描述

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

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保留在同伴的公共环境中?

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天全站免登陆