在Scala REPL中使用什么命令查看实例?

5 投票
2 回答
717 浏览
提问于 2025-04-16 10:00

在Python中:

>>> s = "abc"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', ...

在Scala的REPL中,有没有类似于Python的dir()函数的方法,可以用来查看实例的属性和方法呢?

2 个回答

7

为什么在REPL(交互式编程环境)中,使用制表符补全功能更方便呢?因为它不仅能帮助你快速输入代码,还能在你输入方法名称后显示出相关的参数!而这个功能在技术上相当于使用dir命令,后者可以列出对象的属性和方法。

s.getClass.getMethods
8

当你按下Tab键时,REPL会显示你可以在一个对象上调用的方法:

scala> val s = "abc"
s: java.lang.String = abc

scala> s.<tab>

+                     asInstanceOf          charAt
codePointAt           codePointBefore       codePointCount
compareTo             compareToIgnoreCase   concat
contains              contentEquals         endsWith
equalsIgnoreCase      getBytes              getChars
indexOf               intern                isEmpty
isInstanceOf          lastIndexOf           length
matches               offsetByCodePoints    regionMatches
replace               replaceAll            replaceFirst
split                 startsWith            subSequence
substring             toCharArray           toLowerCase
toString              toUpperCase           trim

想了解更多关于REPL的信息,可以点击 这里

撰写回答