Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the type of a variable when it is not given?

Tags:

types

scala

Assume, we have something like:

val x = "foo".charAt(0)

and let us further assume, we do not know the return type of the method charAt(0) (which is, of course, described in the Scala API). Is there a way, we can find out, which type the variable x has after its definition and when it is not declared explicitly?

UPDATE 1: My initial question was not precise enough: I would like to know (for debugging reasons) what type the variable has. Maybe there is some compiler option to see what type the variable get declared to by Scala's type inference ?

like image 426
John Threepwood Avatar asked Jul 01 '12 19:07

John Threepwood


2 Answers

Suppose you have the following in a source file named Something.scala:

object Something {
  val x = "foo".charAt(0)
}

You can use the -Xprint:typer compiler flag to see the program after the compiler's typer phase:

$ scalac -Xprint:typer Something.scala
[[syntax trees at end of typer]]// Scala source: Something.scala
package <empty> {
  final object Something extends java.lang.Object with ScalaObject {
    def this(): object Something = {
      Something.super.this();
      ()
    };
    private[this] val x: Char = "foo".charAt(0);
    <stable> <accessor> def x: Char = Something.this.x
  }
}

You could also use :type in the REPL:

scala> :type "foo".charAt(0)
Char

scala> :type "foo".charAt _
Int => Char

Your IDE may also provide a nicer way to get this information, as Luigi Plinge points out in a comment above.

like image 108
Travis Brown Avatar answered Oct 27 '22 01:10

Travis Brown


Here's an easier version of Travis first alternative:

dcs@dcs-132-CK-NF79:~/tmp$ scala -Xprint:typer -e '"foo".charAt(0)'
[[syntax trees at end of                     typer]] // scalacmd8174377981814677527.scala
package <empty> {
  object Main extends scala.AnyRef {
    def <init>(): Main.type = {
      Main.super.<init>();
      ()
    };
    def main(argv: Array[String]): Unit = {
      val args: Array[String] = argv;
      {
        final class $anon extends scala.AnyRef {
          def <init>(): anonymous class $anon = {
            $anon.super.<init>();
            ()
          };
          "foo".charAt(0)
        };
        {
          new $anon();
          ()
        }
      }
    }
  }
}
like image 28
Daniel C. Sobral Avatar answered Oct 26 '22 23:10

Daniel C. Sobral