def 不带参数
如果我创建一个函数:
def a(): String = return "some string"
结果将是“a: ()String” 所以我可以使用它带/不带括号
另一方面,如果我创建相同的函数
def a:String = return "some other string"
它只是“a:String” 在这种情况下,我不能将它与括号一起使用。
这两者有什么区别?
If I create a function:
def a(): String = return "some string"
the result would be "a: ()String"
So I can use it with/without brackets
On the other hand if I create the same function
def a:String = return "some other string"
It would be just "a: String"
and in this case I can't use it with brackets.
What is the difference between these two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的实践建议定义没有
()
的没有副作用的函数,并在函数有副作用时在定义站点和调用站点添加()
(例如,println()
而不是println
)。Good practice recommends defining functions that have no side effect without
()
, and to add the()
both at definition site and call site when the function has side effects (e.g.,println()
rather thanprintln
).如果像这样定义
a
,不带括号(注意,return
关键字不是必需的):然后用括号调用它:
a()
,则()
不是方法a
的空参数列表;相反,Scala 会尝试将()
应用于方法a
返回的字符串。当您尝试这样做时收到的错误消息暗示:因此,在第二种情况下,
a()
的含义与第一种情况不同。在第一种情况下,它仅意味着“使用空参数列表调用a
”,在第二种情况下,它意味着“调用a
,然后应用()
到方法的结果”,这将在String
上失败。编辑要在下面的评论中扩展您的第二个问题,这取决于您所说的“同一件事”的确切含义。正如您在 REPL 中看到的,其中一个看起来像是
()java.lang.String
类型,而另一个则具有java.lang.String
类型。看一下下面的内容,其中x
和y
变成了同样的东西:If you define
a
like this, without parentheses (note, thereturn
keyword is not necessary):and then call it with parenthesis:
a()
, then the()
is not the empty argument list for the methoda
; instead, Scala will try to apply the()
to the String that methoda
returns. The error message that you get when you try that hints to that:So, in the second case,
a()
means something else than in the first case. In the first case, it just means "calla
with an empty argument list", and in the second case it means "calla
, then apply()
to the result of the method", which will fail on aString
.edit To expand on your second question in the comments below, it depends on what exactly you mean by "the same thing". As you saw in the REPL one looks like it has the type
()java.lang.String
while the other has the typejava.lang.String
. Have a look at the following, in whichx
andy
turn into the same thing: