代码之家  ›  专栏  ›  技术社区  ›  Max A.

构造函数是否允许用于case类?

  •  2
  • Max A.  · 技术社区  · 15 年前

    我有一个案例班 Stuff )我希望能够通过扩展特性(称之为 Marker )下面是一个repl会话的片段,它演示了我要做的事情:

    scala> trait Marker
    defined trait Marker
    
    scala> case class Stuff(i: Int)
    defined class Stuff
    
    scala> val a = Stuff(1)
    a: Stuff = Stuff(1)
    
    scala> val b = new Stuff(1) with Marker
    b: Stuff with Marker = Stuff(1)
    

    注意如何 a 使用实例化 Stuff.apply() ,在 b 's case I'm calling the case class'构造函数。

    我的问题是: 实例化case类是否使用构造函数kosher? 在我看来,这是因为案例类通常提供的便利,例如 == , .equals() .hashCode() 所有工作。我是否错过了任何能使我所做的 坏东西(tm) ?

    scala> a == b
    res0: Boolean = true
    
    scala> a.equals(b)
    res1: Boolean = true
    
    scala> a.hashCode == b.hashCode
    res2: Boolean = true
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Daniel C. Sobral    15 年前

    方法如下 Stuff.apply 实施时间:

    object Stuff {
      def apply(i: Int): Stuff = new Stuff(i)
    }
    

    所以在使用中没有任何伤害 new Stuff .

        2
  •  3
  •   Alexey Romanov    15 年前

    关于这个问题

    正在使用构造函数kosher实例化case类

    答案是肯定的。有点像

    val b = new Stuff(1)
    

    一点问题也没有。现在, new Stuff(1) with Marker 是不同的,因为 Stuff 已创建。不过,我相信这仍然是没有问题的。我所知道的问题出现在 案例类 从其他case类继承,而不是这样做。但我可能不知道什么。

    编辑:刚在repl中测试匹配:

    scala> val b = new Stuff(1)
    b: Stuff = Stuff(1)
    
    scala> b match {case Stuff(x) => x}
    res0: Int = 1
    
    scala> b match {case Stuff(_) => true}
    res1: Boolean = true
    
    推荐文章