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.
We defined main() function. The main() function is the entry point for the program. In the main() function, we created four variables var1, var2, var3, var4 initialized with some values. After that, we get the type of variables using the getClass method and print the result on the console screen.
Use the getClass Method in Scala The getClass method in Scala is used to get the class of the Scala object. We can use this method to get the type of a variable.
To determine the class of a Scala object we use getClass method. This method returns the Class details which is the parent Class of the instance. Below is the example to determine class of a Scala object. In above example, Calling the printClass method with parameter demonstrates the class Scala.
print. print is the simplest method for displaying output in Scala. It just prints anything you pass it, one after the other, in the same line. print("Hello world!")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With