开发者

var_dump() in Scala

开发者 https://www.devze.com 2023-02-05 06:33 出处:网络
Is there any convenient way to dump all members of a specified object in Scala, li开发者_如何学编程ke var_dump(), PHP function?As mentioned in \"How to Dump/Inspect Object or Variable in Java\" (yes,

Is there any convenient way to dump all members of a specified object in Scala,

li开发者_如何学编程ke var_dump(), PHP function?


As mentioned in "How to Dump/Inspect Object or Variable in Java" (yes, I know, the question is about Scala):

Scala (console) has a very useful feature to inspect or dump variables / object values :

scala> def b = Map("name" -> "Yudha", "age" -> 27)
b: scala.collection.immutable.Map[java.lang.String,Any]

scala> b
res1: scala.collection.immutable.Map[java.lang.String,Any] = Map((name,Yudha), (age,27))

But if you want more details, you can give REPL Scala Utils a try, in order to get a "Easier object inspection in the Scala REPL"

So I've written a utility for use on the Scala REPL that will print out all of the "attributes" of an object.

(Note: "I" being here: Erik Engbrecht, also on BitBucket)

Here's some sample usage:

scala> import replutils._
import replutils._

scala> case class Test(a: CharSequence, b: Int)
defined class Test

scala> val t = Test("hello", 1)
t: Test = Test(hello,1)

scala> printAttrValues(t)
hashCode: int = -229308731
b: int = 1
a: CharSequence (String) = hello
productArity: int = 2
getClass: Class = class line0$object$$iw$$iw$Test

That looks fairly anti-climatic, but after spending hours typing objName to see what's there, and poking at methods, it seems like a miracle.
Also, one neat feature of it is that if the class of the object returned is different from the class declared on the method, it prints both the declared class and the actual returned class.


You might want to look at ToStringBuilder in commons-lang, specificly ToStringBuilder.reflectionToString().


In compiled code, the nicest way is usually just to declare your type as a case class, then use the generated toString method.

Anything else subclassing Product should be just as easy (currently just tuples)

Failing that, write your own toString method, it's usually trivial enough...

0

精彩评论

暂无评论...
验证码 换一张
取 消