[英]print type of variable in Scala
Is there a neat method could print the class name of a variable in Scala?是否有一种简洁的方法可以在 Scala 中打印变量的类名?
Sometimes I see val result = foo(a,b,c)
, since method foo
may return different types of object and if I could print class type of result, it will be great.有时我看到
val result = foo(a,b,c)
,因为方法foo
可能返回不同类型的对象,如果我可以打印结果的类类型,那就太好了。
Quick and dirty trick I often use我经常使用的快速而肮脏的技巧
val result: Nothing = foo(a,b,c)
The compiler will raise an error, providing you information about the actual return type it found.编译器将引发错误,为您提供有关它找到的实际返回类型的信息。
Example from the REPL来自 REPL 的示例
scala> val foo: Nothing = 42
<console>:1: error: type mismatch;
found : Int(42) // <---- this is what you care about
required: Nothing
val foo: Nothing = 42
If you use an IDE, you may use more "sophisticated" options:如果您使用 IDE,您可以使用更“复杂”的选项:
Use Object.getClass
method.使用
Object.getClass
方法。
See Scala Cookbook参见Scala 食谱
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.