相当于 scala 中的 python repr()
scala 中是否有相当于 Python 的 repr 函数?
即,您可以给任何 scala 对象提供一个函数,它将生成该对象的字符串表示形式,该对象是有效的 scala 代码。
例如:
val l = List(Map(1 -> "a"))
print(repr(l))
会产生
List(Map(1 -> "a"))
Is it there an equivalent of Pythons repr
function in 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.
eg:
val l = List(Map(1 -> "a"))
print(repr(l))
Would produce
List(Map(1 -> "a"))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个对象大多只有
toString
方法。 (继承自 Java。)这可能会也可能不会产生可解析的表示。在大多数一般情况下,它可能不会; Python 中没有真正的约定,但一些集合类至少尝试这样做。 (只要它们不是无限的。)当涉及字符串时,它当然已经达到了崩溃的程度
,但是,为了正确的表示,需要
据我所知,Scala 中没有这样的东西。不过,一些序列化库可能对此有所帮助。
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
however, for a proper representation, one would need
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.
基于Java相当于Python repr()?的逻辑,我写了这个小函数:
我已经尝试过一些值并且它似乎可以工作,尽管我很确定在 U+FFFF 之上坚持使用 Unicode 字符会导致问题。
Based on the logic at Java equivalent of Python repr()?, I wrote this little function:
I've tried it with a few values and it seems to work, though I'm pretty sure sticking in a Unicode character above U+FFFF would cause problems.
如果您处理案例类,您可以混合以下特征
StringMaker
,这样即使它们的参数是字符串,在此类案例类上调用 toString 也将起作用:将导致:
因此您可以解析回第一个表达,但不是第一个。
If you deal with case classes, you can mix in the following trait
StringMaker
, so that calling toString on such case classes will work even if their arguments are strings:will result in:
So you can parse back the firsst expression, but not the first one.
不,Scala 中没有这样的功能。
No, there is no such feature in Scala.