如何在案例类伴侣中覆盖应用 [英] How to override apply in a case class companion

查看:43
本文介绍了如何在案例类伴侣中覆盖应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况是这样的.我想像这样定义一个案例类:

So here's the situation. I want to define a case class like so:

case class A(val s: String)

并且我想定义一个对象以确保当我创建类的实例时,s"的值总是大写,如下所示:

and I want to define an object to ensure that when I create instances of the class, the value for 's' is always uppercase, like so:

object A {
  def apply(s: String) = new A(s.toUpperCase)
}

然而,这不起作用,因为 Scala 抱怨 apply(s: String) 方法被定义了两次.我知道 case 类语法会自动为我定义它,但是没有另一种方法可以实现这一点吗?我想坚持使用 case 类,因为我想用它来进行模式匹配.

However, this doesn't work since Scala is complaining that the apply(s: String) method is defined twice. I understand that the case class syntax will automatically define it for me, but isn't there another way I can achieve this? I'd like to stick with the case class since I want to use it for pattern matching.

推荐答案

冲突的原因是 case 类提供了完全相同的 apply() 方法(相同的签名).

The reason for the conflict is that the case class provides the exact same apply() method (same signature).

首先我建议你使用require:

First of all I would like to suggest you use require:

case class A(s: String) {
  require(! s.toCharArray.exists( _.isLower ), "Bad string: "+ s)
}

如果用户尝试创建一个 s 包含小写字符的实例,这将抛出异常.这是案例类的一个很好的用途,因为你放入构造函数的也是你在使用模式匹配时得到的(match).

This will throw an Exception if the user tries to create an instance where s includes lower case chars. This is a good use of case classes, since what you put into the constructor also is what you get out when you use pattern matching (match).

如果这不是您想要的,那么我会将构造函数设为 private 并强制用户 only 使用 apply 方法:

If this is not what you want, then I would make the constructor private and force the users to only use the apply method:

class A private (val s: String) {
}

object A {
  def apply(s: String): A = new A(s.toUpperCase)
}

如您所见,A 不再是case class.我不确定具有不可变字段的 case 类是否用于修改传入的值,因为名称case class"意味着应该可以使用 match 提取(未修改的)构造函数参数.

As you see, A is no longer a case class. I am not sure if case classes with immutable fields are meant for modification of the incoming values, since the name "case class" implies it should be possible to extract the (unmodified) constructor arguments using match.

这篇关于如何在案例类伴侣中覆盖应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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