scala - 如何从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)
}
}
然后它开始永无止境的递归。
解决方案
如果您希望对所有实例强制执行规则,请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)
推荐阅读
- php - 使用 SQL 在 Woocommerce 中获取具有特定属性术语和特定类别术语的产品
- php - Twilio 聚集延迟
- sql - 将 For Xml 和 With 子句的结果分配给变量
- java - 如何处理嵌入的复合键?
- c++ - LLVM - 在每个循环中检测一个函数并将所有局部变量传递给它
- node.js - socket.io-client on('message') 不工作
- c++ - 这个 CPython 代码中的“&&x”是什么意思?
- apache-spark - Spark-submit 失败,返回码为 13,例如 wordCount
- css - 反应:让 div 占据所有可用的高度
- c - Ptrace 允许写入可执行程序段,但 process_vm_writev 不允许