【问题标题】:Override method in case object without changing fields在不更改字段的情况下覆盖案例对象中的方法
【发布时间】:2014-06-16 17:58:09
【问题描述】:
case class A(a:Int, b:Int) {
  def f(){println(a)}
}
val o1 = A(3,3)

val o2 = new A(o1.a,o1.b) {override def f(){println(b)}}  //too long when there are a lot of parameters

这里我必须将 o1 参数传递给 o2,但在现实生活中我有更多的参数。我知道我可以像这样复制案例对象

 o2 = o1.copy

有什么方法可以将复制与覆盖方法结合起来吗?

【问题讨论】:

    标签: scala case-class overriding


    【解决方案1】:

    不确定是否有一种简单的方法可以将copy 与覆盖结合起来。但是,作为替代方案,您可以考虑重载案例类构造函数(以获取案例类对象),如下所示:

    case class A(x: Int, y: String) {
    
      def this(a : A) = this(a.x, a.y)
    
      def f() { println(x)}
    }
    

    然后,您可以通过仅传递 1 个参数来创建 A 对象实例(具有覆盖):

    val o1 = A(30, "Test")
    val o2 = new A(o1) { override def f() { println(y)} }
    

    显然这并不能完全解决长参数问题,因为您在定义构造函数时仍然需要列出它们。虽然如果您要处理多个具有不同行为的 A 对象,那么与每次都指定完整列表相比,这应该是一个很大的改进。

    【讨论】:

    • 为什么我不能在构造函数中使用copy来返回a的副本?
    • 这是 Scala 的要求。根据“Scala 编程”:In Scala, every auxiliary constructor must inkove another contructor of the same class as its first action. The net effect of this rule is that every constructor invocation in Scala will end up eventually calling the primary constructor of the class. The primary constructor is thus the single point of entry of a class. 参见此处:stackoverflow.com/questions/10426146/… 了解更多详情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2011-03-11
    • 2014-06-10
    • 2012-09-09
    • 2022-08-06
    相关资源
    最近更新 更多