简体   繁体   English

如何在Scala中打印出列表的类型?

[英]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? 这可能在Scala中吗? The standard .getClass doesnt seem to work here. 标准.getClass似乎在这里工作。 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 . 也就是说,我的理解是在Scala 2.12中ClassTagTypeTag优于Manifest Here's a way to do this with TypeTag : 以下是使用TypeTag执行此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. 这样做的原因是类型擦除意味着在运行时,使用泛型参数String声明List的事实根本就不存在了。 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. ClassTagTypeTag添加上下文绑定意味着您为ClassTag[T]TypeTag[T]引入了一个隐式参数,编译器会在遇到依赖项时为您生成该参数。 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. 这些参数对可能会丢失的类型信息进行编码,并且可以在类似于typeOf方法中使用,以提取比类实例本身更多的类型信息。

You can declare a function typeWriter like this 你可以像这样声明一个函数typeWriter

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 当您使用给定值作为输入调用typeWriter函数时,您将获得类型信息

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 repl模式,则可以使用':type'获取类型级别信息

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

scala> :type ex
List[String]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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