简体   繁体   中英

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!

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM