0

In the Scala repl if I evaluate :

val lines : String = ("a1 , test1 , test2 , a2 , test3 , test4")
    lines.split(",").grouped(3).toList 

I receive this on save :

//> res0: List[Array[String]] = List(Array("a1 ", " test1 ", " test2 "), Array("
                                                  //|  a2 ", " test3 ", " test4"))

I would like to be able to print this information to the console, the value of res0

So something like printTypeInformation(lines.split(",").grouped(3).toList) will print same value as res0 above. I think I could achieve this for above type by iterating over the List printing the values and type information. But is there a more generic method so that this information can be printed for any type ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

1

As pointed out by @Jatin , you can do this with manifests:

def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
val lines : String = ("a1 , test1 , test2 , a2 , test3 , test4")
val xs = lines.split(",").grouped(3).toList
println(manOf(xs))
// scala.collection.immutable.List[Array[java.lang.String]]
Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • can the values of the type information also be accessed using manifests , so in this case print the values of the Array ? – blue-sky Jan 30 '14 at 10:55
  • @Adrian in general case REPL uses ordinary .toString method (you can check this with `class Foo { override def toString = "I'm bar" }; new Foo`), so `manOf(xs) + "=" + xs.toString` is quite close to what you want to archive, though REPL has special cases for Arrays and I guess some other classes. – om-nom-nom Jan 30 '14 at 11:07
1

The answer is close to the one from om-nom-nom, but as of scala 2.10 i think better to use TypeTags:

scala> "a1 , test1 , test2 , a2 , test3 , test4"
res3: String = a1 , test1 , test2 , a2 , test3 , test4

scala> res3.split(",").grouped(3).toList
res4: List[Array[String]] = List(Array("a1 ", " test1 ", " test2 "), Array(" a2 ", " test3 ", " test4"))

scala> def typped[T: TypeTag](obj: T) = typeOf[T]
typped: [T](obj: T)(implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.Type

scala> typped(res4)
res5: reflect.runtime.universe.Type = scala.List[scala.Array[String]]
4lex1v
  • 21,367
  • 6
  • 52
  • 86