tags:

views:

98

answers:

1

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?

+8  A: 

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: <?>
retronym
@retronym, thanks for your answer. Although it's too difficult for me to understand now(I just learn it for 2 days), but I think I will read it carefully someday:)
Freewind