How to determine the type of a variable if it is not specified?

Suppose we have something like:

val x = "foo".charAt(0) 

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

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 kind of compiler option to find out what type of variable is declared using Scala output?

+6
source share
4 answers

Suppose the following is in the source file called Something.scala :

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

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

 $ 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 can also use :type in REPL:

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

Your IDE may also provide a more convenient way to get this information, as Luigi Pling notes in the comment above.

+7
source

Use this method for the problem:

 x.getClass 
+3
source

Here's a simpler version of the first Travis 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(); () } } } } } 
+3
source

If you use IntelliJIDEA to display the Type Information action in the editor, go to the value and press Alt + = for Windows and Ctrl + Shift + P for Mac:

enter image description here

I am very comfortable writing code.

+1
source

Source: https://habr.com/ru/post/919449/


All Articles