Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out the type of a list in Scala?

Here's an example of what I'm trying to do:

val ex = List[String]("a", "b", "c") typePrinter(ex) //prints out "List[String]"

Is this possible in Scala? The standard .getClass doesnt seem to work here. Thanks!

like image 878
Bob Risky Avatar asked Dec 17 '25 12:12

Bob Risky


2 Answers

Chaitanya's approach is the correct one. That said, my understanding is that in Scala 2.12 ClassTag and TypeTag are preferred over Manifest. Here's a way to do this with TypeTag:

import scala.reflect.runtime.universe._


def getClassName[T : TypeTag](input: T) : String = {
  typeOf[T].toString
}
val ex = List[String]("a", "b", "c")
println(getClassName(ex)) // prints "List[String]"

The reason for this is that type erasure means that at runtime, the fact that your List was declared with generic parameter String is simply not there anymore. Adding a context bound for ClassTag or TypeTag means that you introduce an implicit parameter for ClassTag[T] or TypeTag[T], which the compiler will generate for you when it encounters the dependency. These parameters encode the type information that would be lost otherwise, and can be used in methods like typeOf to pull out more type information than is available on the class instance itself.

like image 150
Astrid Avatar answered Dec 19 '25 05:12

Astrid


You can declare a function typeWriter like this

def typePrinter[T: Manifest](t: T): Manifest[T] = manifest[T]

Then for the input

val ex = List[String]("a", "b", "c")

when you invoke the typeWriter function with the given value as the input you will get the type information

typePrinter(ex)

output as

res0: Manifest[List[String]] = scala.collection.immutable.List[java.lang.String]

Also if you are in scala repl mode you can get the type level information by using ' :type '

scala> val ex = List[String]("a", "b", "c")
ex: List[String] = List(a, b, c)

scala> :type ex
List[String]
like image 41
Chaitanya Waikar Avatar answered Dec 19 '25 06:12

Chaitanya Waikar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!