Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var_dump() in Scala

Tags:

scala

Is there any convenient way to dump all members of a specified object in Scala,
like var_dump(), PHP function?

like image 914
tototoshi Avatar asked Jan 19 '11 14:01

tototoshi


People also ask

What is Var_dump () function?

The function var_dump() displays structured information (type and value) about one or more expressions/variables. Arrays and objects are explored recursively with values indented to show structure. All public, private and protected properties of objects will be returned in the output.

What is the difference between Var_dump () and Print_r ()?

var_dump() displays values along with data types as output. print_r() displays only value as output. It does not have any return type. It will return a value that is in string format.

Why Var_dump () is preferable over Print_r ()?

It's too simple. The var_dump() function displays structured information about variables/expressions including its type and value. Whereas The print_r() displays information about a variable in a way that's readable by humans. Example: Say we have got the following array and we want to display its contents.


2 Answers

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.

like image 176
VonC Avatar answered Sep 29 '22 08:09

VonC


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

like image 24
sblundy Avatar answered Sep 29 '22 10:09

sblundy