[英]How can I determine the type of a variable when it is not given?
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). 让我们进一步假设,我们不知道方法
charAt(0)
的返回类型(当然,这在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? 有没有一种方法,我们可以找出变量
x
在定义之后有什么类型,什么时候没有明确声明呢?
UPDATE 1: My initial question was not precise enough: I would like to know (for debugging reasons) what type the variable has. 更新1:我最初的问题不够精确:我想(出于调试原因)想知道变量的类型。 Maybe there is some compiler option to see what type the variable get declared to by Scala's type inference ?
也许有一些编译器选项可以查看Scala的类型推断将变量声明为哪种类型?
Suppose you have the following in a source file named Something.scala
: 假设您在名为
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: 您可以使用
-Xprint:typer
编译器标志在编译器的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 could also use :type
in the REPL: 您也可以在REPL中使用
:type
:
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. 正如Luigi Plinge在上面的评论中指出的那样,您的IDE可能还会提供一种更好的方式来获取此信息。
使用此方法解决问题:
x.getClass
Here's an easier version of Travis first alternative: 这是Travis第一个替代方案的简单版本:
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();
()
}
}
}
}
}
If you are using IntelliJIDEA , to show Type Info action in Editor, navigate to the value and press Alt
+ =
for Windows and Ctrl
+ Shift
+ P
for Mac: 如果使用的是IntelliJIDEA ,要在编辑器中显示“类型信息”操作,请导航至该值,然后对于Windows按
Alt
+ =
,对于Mac Ctrl
+ Shift
+ P
:
I find it very handy when writing code. 我在编写代码时非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.