首页 > 解决方案 > 如何从scala案例类中的伴随应用方法调用构造函数?

问题描述

case class Host(
                name: String,
                http: String
                )

我想在课堂上将所有给定的名称设为小写。
当我尝试像这样覆盖应用时:

case class Host(
                name: String,
                http: String
                )

object Host{
  def apply(
            name: String,
            http: String
           ): Host= {
    Host(name.toLowerCase, http)
  }
}

然后它开始永无止境的递归。

标签: scala

解决方案


如果您希望对所有实例强制执行规则,请Host考虑将主构造函数设为私有,如下所示

case class Host private (
  name: String,
  http: String
)

并按照@user 的其余部分回答。如果您不将其设为私有,则可以通过调用主构造函数new而不是同伴的apply工厂方法来轻松绕过该规则

Host("PICARD", "starfleet.org")            // OK     
// res0: Host = Host(picard,starfleet.org)

new Host("PICARD", "starfleet.org")        // oops!
// res1: Host = Host(PICARD,starfleet.org)



推荐阅读