如何在 Scala 中将集合打印为有效代码



>假设我有

val x = List("a","b","c")

我想要一个函数f调用时返回

List("a","b","c")

目前,println(x)只打印List(a,b,c)在编译/粘贴到 Scala-T笔记本或单元测试中时不会编译。

我很难找到一个也适用于Seq[Double]等的通用解决方案,我设法通过重新添加引号来获得Seq[String]的东西,但我无法为所有集合类型获得合适的解决方案

听起来你想要自定义类型类Show

trait Show[T] {
def show(t: T): String
}
trait LowPriorityShow {
implicit def default[T]: Show[T] = _.toString
}
object Show extends LowPriorityShow {
implicit val str: Show[String] = s => s""""$s""""
// other exceptions for element types
implicit def list[T: Show]: Show[List[T]] = _.map(show(_)).mkString("List(", ",", ")")
implicit def seq[T: Show]:  Show[Seq[T]]  = _.map(show(_)).mkString("Seq(", ",", ")")
// other exceptions for collection types
}
def show[T](t: T)(implicit s: Show[T]): String = s.show(t)
val x = List("a","b","c")
show(x) //List("a","b","c")
val x1 = Seq("a","b","c")
show(x1) //Seq("a","b","c")

您可以尝试将集合的实例(Show.listShow.seq...(替换为更通用的

实例
import shapeless.Typeable
implicit def collection[Col[X] <: Iterable[X], T: Show](implicit ev: Typeable[Col[_]]): Show[Col[T]] = {
val col = Typeable[Col[_]].describe.takeWhile(_ != '[')
_.map(show(_)).mkString(s"$col(", ",", ")")
}

你必须检查自己,结果是否总是在 Scala 中是有效的代码。

最新更新