gpt4 book ai didi

scala - 案例类 toString 与 Iterable 特性纠缠在一起?

转载 作者:行者123 更新时间:2023-12-01 03:18:15 24 4
gpt4 key购买 nike

似乎当一个案例类扩展 Iterable[T] , toString方法变了。

case class MyPoint(x: Int, y: Int)

case class MyOtherPoint(x: Int, y: Int) extends Iterable[Double] {
def iterator: Iterator[Double] = Iterator.fill(4)(1.0)
}

object Main extends App {
val my_pt = MyPoint(4,5)
println(my_pt) // MyPoint(4,5)
// println(my_pt.iterator) // ERROR, iterator is not a member of MyPoint
val my_other_pt = MyOtherPoint(4, 5)
println(my_other_pt) // MyOtherPoint(1.0, 1.0, 1.0, 1.0)
println(my_other_pt.productIterator.toList) // List(4, 5)
}

这似乎很不幸,特别是考虑到虽然 case 类扩展了 Product默认情况下,因此有 productIterator ,他们不应该扩展 Iterable .

这是 Scala 编译器中的错误吗?

最佳答案

Is this a bug in the Scala compiler?



不,这是规范中定义的行为( section §5.3.2 ,重点是我的):

Every case class implicitly overrides some method definitions of class scala.AnyRef unless a definition of the same method is already given in the case class itself or a concrete definition of the same method is given in some base class of the case class different from AnyRef. In particular:

  • Method toString: String returns a string representation which contains the name of the class and its elements.


你看到的是 Iterable的结果继承 TraversableLike ,其中有以下 toString覆盖:
override def toString = mkString(stringPrefix + "(", ", ", ")")

此外,如果您在 Xprint:jvm 下编译可以看到 MyOtherPoint继承的很多方法,包括覆盖 toString :
case class MyOtherPoint extends Object with Iterable with Product with Serializable {
// removed all other methods for brevity
override def toString(): String = MyOtherPoint.super.toString();
}

关于scala - 案例类 toString 与 Iterable 特性纠缠在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com