scala Scala中变量的打印类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36700010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
print type of variable in Scala
提问by Lin Ma
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 foomay 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可能返回不同类型的对象,如果我可以打印结果的类类型,那就太好了。
回答by Gabriele Petronella
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,您可以使用更“复杂”的选项:

