Scala 方法调用中括号的规则是什么? [英] What is the rule for parenthesis in Scala method invocation?

查看:49
本文介绍了Scala 方法调用中括号的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

toList 不是一个将某些东西转换成 List 的方法吗?

如果是,那么为什么我不能使用括号呢?我一定在这里遗漏了一些更基本的东西.

示例如下:

val l = Array(1,2,3).toList//工作正常val l = Array(1,2,3).toList()//给出以下错误

<块引用>

方法的参数不足:(n: Int)Int in trait线性序列优化.未指定值参数 n.

解决方案

如果一个方法被定义为

def toList = {/* 东西 */}

那么它必须被称为

object.toList

没有额外的括号.我们说这个方法有零个参数列表.

我们也可以定义一个参数列表,但什么都不放在里面:

def toList() = {/* 东西 */}

现在,我们可以调用其中一个

object.toList()object.toList

因为 Scala 允许在方法调用中省略括号的快捷方式.

就 JVM 而言,第一个定义(零参数列表")和第二个(一个空参数列表")之间没有区别.但是 Scala 保持着区别.这是否是一个好主意值得商榷,但当你意识到我们也可以

def toList()() = {/* 东西 */}

这被称为两个空参数列表,然后调用任何一个

object.toList()()object.toList()object.toList

现在,如果我们要将其转换为函数,我们会将其输入为

() =>() =>T/* T 是某物的返回值 */

而第二个定义是

() =>吨

这在概念上明显不同,即使实际上你以相同的方式使用它(什么都不放,迟早会得到一个 T).

无论如何,toList 不需要任何参数,Scala 标准是不使用括号,除非方法改变对象本身(而不是仅仅返回某些东西),所以它是 def toList 之后没有任何括号.因此,您只能将其称为 object.toList.

Isn't toList a method that converts something into a List?

If yes so why can't I use parenthesis with it? I must be missing something more fundamental here.

Here is the example:

val l = Array(1,2,3).toList // works fine

val l = Array(1,2,3).toList() // gives the error below

Not enough arguments for method apply: (n: Int)Int in trait LinearSeqOptimized. Unspecified value parameter n.

解决方案

If a method is defined as

def toList = { /* something */ }

then it must be called as

object.toList

with no extra parentheses. We say that this method has zero parameter lists.

We could also define a parameter list but put nothing in it:

def toList() = { /* something */ }

Now, we could call either of

object.toList()
object.toList

since Scala allows the shortcut of omitting parentheses on method calls.

As far as the JVM is concerned, there is no difference between the first definition ("zero parameter lists") and the second ("one empty parameter list"). But Scala maintains a distinction. Whether this is a good idea or not is debatable, but the motivation might be clearer when you realize that we can also

def toList()() = { /* something */ }

which is known as two empty parameter lists, and then call any of

object.toList()()
object.toList()
object.toList

and now, if we were to convert this into a function, we would type it as

() => () => T   /* T is the return value of the something */

while the second definition would be

() => T

which is clearly different conceptually, even if practically you use it the same way (put in nothing and sooner or later get out a T).

Anyway, toList doesn't need any parameters, and the Scala standard is to leave off the parens unless the method changes the object itself (rather than just returning something), so it's def toList without any parens afterwards. And thus you can only call it as object.toList.

这篇关于Scala 方法调用中括号的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆