【发布时间】:2021-06-24 11:29:39
【问题描述】:
当我执行这段代码时:
object CustomList extends App{
sealed trait CustomList[+A]
case object Nil extends CustomList[Nothing]
case class Cons[+A](head: A, tail: CustomList[A]) extends CustomList[A]
def apply[A](as: A*): CustomList[A] = // Variadic function syntax
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
val customList : CustomList[Int] = CustomList(1 ,2 ,3)
println(customList)
val list : List[Int] = List(1,2,3)
println(list)
}
打印以下内容:
Cons(1,Cons(2,Cons(3,Nil)))
List(1, 2, 3)
CustomList 是我自己实现的列表数据结构,当函数println 应用于它时,我试图打印类似的输出。所以应该打印CustomList(1, 2, 3) 而不是Cons(1,Cons(2,Cons(3,Nil))) 打印
println 的参数将参数转换为字符串并打印:
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes {@link #print(String)} and then
* {@link #println()}.
*
* @param x The {@code Object} to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
但我不确定如何创建正确的类型以以相同格式打印CustomList。
是否有我需要实施的方法来实现相同的行为?
【问题讨论】:
-
您将看到 Cons 和 Nil 案例类/对象提供的
toString的当前实现。您可以覆盖它,一种常见的方法是定义一个mkString方法,并在主要特征中执行此操作:override def toString(): String = this.mkString("CustomList(", ", ", ")")这或多或少与 stdlib 列表相同。请注意,由于 String 连接在 JVM 中非常慢,这是恕我直言可变性非常受欢迎的情况之一,我将使用 StringBuilder 来实现 @987654333 @方法。 -
啊我忘了,
override也应该是final以避免意外。