How to avoid scala's case class default toString function being overridden?

后端 未结 3 1866
Happy的楠姐
Happy的楠姐 2020-12-16 17:05

Scala case class has a default toString function. But when this case class extends a trait with an existing toString() function, it will be rendered useless. How can I preve

相关标签:
3条回答
  • 2020-12-16 17:20

    OK here is the easist answer:

    override def toString = ScalaRunTime._toString(this)
    

    end of story:)

    0 讨论(0)
  • 2020-12-16 17:25

    Here's a workaround I think may work, it may be too much ceremony, you decide. It involves a trait.

    trait StandardToString { this:Product =>
      override def toString = productPrefix + productIterator.mkString("(", ",", ")")
    }
    

    Now trying it with some samples:

    trait Human {
       override def toString() = "Human"
    }
    
    case class European(firstName:String) extends Human
    

    and running it with the trait:

    scala> new European("Falco") with StandardToString
    res0: European with StandardToString = European(Falco)
    

    of course with the trait you are left with

    scala> new European("Adele")
    res1: European = Human
    
    0 讨论(0)
  • 2020-12-16 17:26

    It's more precise to say that the case class toString is not generated, rather than that it is overridden.

    This isn't much of an answer or workaround.

    scala> trait X { override def toString = "X" }
    defined trait X
    
    scala> case class Y(i: Int) extends X
    defined class Y
    
    scala> Y(42)
    res0: Y = X
    
    scala> case class Y(i: Int)
    defined class Y
    
    scala> class Z(x: Int) extends Y(x) with X { override def toString = super[Y].toString }
    defined class Z
    
    scala> new Z(42)
    res1: Z = Y(42)
    

    You can't do that with a trait:

    scala> trait R extends Y { override def toString = super[Y].toString }
    <console>:9: error: Implementation restriction: traits may not select fields or methods from super[C] where C is a class
           trait R extends Y { override def toString = super[Y].toString }
                                                       ^
    
    0 讨论(0)
提交回复
热议问题