简体   繁体   中英

print type of variable in Scala

Is there a neat method could print the class name of a variable in 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.

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

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:

Use Object.getClass method.

See Scala Cookbook

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