Equivalent to pythons repr () in scala

Is there an equivalent pythons repr function in scala?

Those. the function you can give to any scala object will produce a string representation of the object, which is valid scala code.

eg:

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

Will produce

 List(Map(1 -> "a")) 
+6
source share
4 answers

On each object, only the toString method exists. (Inherited from Java.) This may or may not lead to analysis. In most common cases, this probably will not; there is no real agreement for this, as in Python, but some of the collection classes at least try. (Until they are endless.)

The point where it breaks is, of course, already reached when the lines are involved.

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

however, for a proper presentation it would be necessary

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

As far as I know, there is no such thing in Scala. However, some of the serialization libraries may be useful for this.

+5
source

Based on the logic in the Python Java equivalent of repr ()? I wrote this little function:

 object Util { def repr(s: String): String = { if (s == null) "null" else s.toList.map { case '\0' => "\\0" case '\t' => "\\t" case '\n' => "\\n" case '\r' => "\\r" case '\"' => "\\\"" case '\\' => "\\\\" case ch if (' ' <= ch && ch <= '\u007e') => ch.toString case ch => { val hex = Integer.toHexString(ch.toInt) "\\u%s%s".format("0" * (4 - hex.length), hex) } }.mkString("\"", "", "\"") } } 

I tried it with multiple values ​​and it seems to work, although I'm sure sticking to the Unicode character above U + FFFF will cause problems.

+3
source

If you StringMaker case classes, you can mix StringMaker in the following StringMaker , so calling toString in such case classes will work, even if their arguments are strings:

 trait StringMaker { override def toString = { this.getClass.getName + "(" + this.getClass.getDeclaredFields.map{ field => field.setAccessible(true) val name = field.getName val value = field.get(this) value match { case s: String => "\"" + value + "\"" //Or Util.repr(value) see the other answer case _ => value.toString } } .reduceLeft{_+", "+_} + ")" } } trait Expression case class EString(value: String, i: Int) extends Expression with StringMaker case class EStringBad(value: String, i: Int) extends Expression //w/o StringMaker val c_good = EString("641", 151) val c_bad = EStringBad("641", 151) 

will result in:

 c_good: EString = EString("641", 151) c_bad: EStringBad = EStringBad(641,151) 

So, you can parse the first expression, but not the first.

+2
source

No, there is no such function in Scala.

0
source

Source: https://habr.com/ru/post/899801/