Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inspect an object in script like in scala console?

Tags:

scala

inspect

When I use scala console, it prints an object in a clear style, e.g.

scala> val mike = ("mike", 40, "New York")
mike: (java.lang.String, Int, java.lang.String) = (mike,40,New York)

But if I write in a script file, like:

val mike = ("mike", 40, "New York")
println(mike)

It only prints:

(mike,40,New York)

How can I do in script file like the scala console? Is there a method for this?

like image 747
Freewind Avatar asked Jul 27 '10 12:07

Freewind


1 Answers

You can retrieve the type of a variable with a Manifest:

scala> def dump[T: Manifest](t: T) =  "%s: %s".format(t, manifest[T])
dump: [T](t: T)(implicit evidence$1: Manifest[T])String

scala> dump((1, false, "mike"))
res3: String = (1,false,mike): scala.Tuple3[Int, Boolean, java.lang.String]

If the inferred type T is an abstract type, there must be an implicit Manifest[T] provided, otherwise this won't compile.

scala> trait M[A] {
     |    def handle(a: A) = dump(a)
     | }
<console>:7: error: could not find implicit value for evidence parameter of type
 Manifest[A]
          def handle(a: A) = dump(a)

You could make a version that provides a default for the implicit Manifest[T] parameter in this case:

scala> def dump2[T](t: T)(implicit mt: Manifest[T] = null) = "%s: %s".format(t,
     |    if (mt == null) "<?>" else mt.toString)
dump2: [T](t: T)(implicit mt: Manifest[T])String

scala> trait M[A] {
     |    def handle(a: A) = dump2(a)
     | }
defined trait M

scala> (new M[String] {}).handle("x")
res4: String = x: <?>
like image 146
retronym Avatar answered Oct 03 '22 23:10

retronym