Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print type of variable in Scala

Tags:

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.

like image 579
Lin Ma Avatar asked Apr 18 '16 16:04

Lin Ma


People also ask

How do you print the datatype of a variable in Scala?

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.

How to see type of variable in Scala?

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.

How to find type of object in Scala?

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.

How to print object in 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!")


2 Answers

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:

  • Scala IDE: http://scala-ide.org/docs/current-user-doc/features/typingviewing/show-type-of-selection.html
  • IntelliJ: How do I view the type of a scala expression in IntelliJ
like image 88
Gabriele Petronella Avatar answered Sep 24 '22 15:09

Gabriele Petronella


Use Object.getClass method.

See Scala Cookbook

like image 16
Alexander Reshytko Avatar answered Sep 22 '22 15:09

Alexander Reshytko