简体   繁体   English

如何漂亮地打印scala类型?

[英]How to pretty print a scala type?

I want to show the user a value, a simplified type and the original type. 我想向用户显示一个值,一个简化类型和原始类型。

I'm using pprint library for the value and scala.Manifest for the type. 我正在使用pprint库作为值和scala.Manifest作为类型。

def render[T](a: T)(implicit m: Manifest[T]): (String, String, String) =
  (pprint(a), simplify(m), m.toString)

I want to implement this simplify function. 我想实现这个simplify功能。

It would remove common imports 它将删除普通进口

def simplify[T](m: Manifest[T]): String =
  m.toString
   .replaceAll("scala.", "")
   .replaceAll("scala.collection.immutable.", "")
   .replaceAll("scala.collection.mutable.", "")
   .replaceAll("java.lang.", "")

but m.toString has the following drawback 但是m.toString具有以下缺点

  • desugars functions, (Int, Int) => Int becomes scala.Function2[Int, Int, Int] desugars函数, (Int, Int) => Int成为scala.Function2[Int, Int, Int]
  • desugars tuples, (Int, Int) becomes scala.Tuple2[Int, Int] desugars元组, (Int, Int)成为scala.Tuple2[Int, Int]

type pretty print is implemented in ammonite-repl with TPrint[T] 使用TPrint[T]TPrint[T] -repl中实现漂亮的打印类型

libraryDependencies += "com.lihaoyi" % "ammonite-repl" % "0.5.4" cross CrossVersion.full

import ammonite.repl.frontend.TPrint
val config = pprint.Config.Defaults.PPrintConfig
def render[T](a: T)(implicit tp: TPrint[T], m: Manifest[T]): (String, String, String) =
  (pprint(a), tp.render(config), m.toString)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM