26

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.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Lin Ma
  • 9,739
  • 32
  • 105
  • 175

2 Answers2

35

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:

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • Thanks Gabriele, vote up. Is there a way to print type dynamically since the method `foo` has different types of return dynamically and will decide at run time. – Lin Ma Apr 18 '16 at 17:10
  • 1
    @LinMa, that's a very different question than the one you asked :) I definitely need a more comprehensive example to give an appropriate answer – Gabriele Petronella Apr 18 '16 at 17:11
  • 1
    If you want a real runtime class just use `result.getClass`. `Set(1).getClass` would output `class scala.collection.immutable.Set$Set1` – Łukasz Apr 18 '16 at 17:12
  • Thanks Gabriele, vote up and let me mark your reply as answer first. Then ask more. :)) – Lin Ma Apr 18 '16 at 17:16
21

Use Object.getClass method.

See Scala Cookbook

Alexander Reshytko
  • 2,126
  • 1
  • 20
  • 28