相当于scala中的pythons repr() [英] equivalent of pythons repr() in scala

查看:48
本文介绍了相当于scala中的pythons repr()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala 中是否有等效于 Python 的 repr 函数?

Is it there an equivalent of Pythons repr function in scala?

即一个函数,你可以给任何 scala 对象,它会产生一个对象的字符串表示,这是有效的 Scala 代码.

Ie a function which you can give any scala object an it will produce a string representation of the object which is valid scala code.

例如:

val l = List(Map(1 -> "a"))

print(repr(l))

会产生

List(Map(1 -> "a"))

推荐答案

每个对象上大多只有 toString 方法.(继承自 Java.)这可能会也可能不会导致可解析的表示.在大多数通用情况下,它可能不会;没有像 Python 那样真正的约定,但一些集合类至少尝试这样做.(只要它们不是无限的.)

There is mostly only the toString method on every object. (Inherited from Java.) This may or may not result in a parseable representation. In most generic cases it probably won’t; there is no real convention for this as there is in Python but some of the collection classes at least try to. (As long as they are not infinite.)

当涉及到字符串时,当然已经到了崩溃的地步

The point where it breaks down is of course already reached when Strings are involved

"some string".toString == "some string"

然而,为了适当的表示,人们需要

however, for a proper representation, one would need

repr("some string") == "\"some string\""

据我所知,Scala 中没有这种东西.不过,某些序列化库可能对此有所帮助.

As far as I know there is no such thing in Scala. Some of the serialisation libraries might be of some help for this, though.

这篇关于相当于scala中的pythons repr()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆