更新时间:2022-04-29 04:43:58
其他答案处理您的具体情况.不过,你问的是一般情况,所以我会尝试从这个角度回答.
The other answers deal with your specific case. You asked about the general case, however, so I'll attempt to answer from that perspective.
首先,def
用于定义方法,不是函数(现在***了解这种区别).但是,您是对的,index
是该方法的名称.
First off, def
is used to define a method, not a function (better to learn that difference now). But, you're right, index
is the name of that method.
现在,与您可能熟悉的其他语言(例如 C、Java)不同,Scala 允许您使用表达式定义方法(如使用赋值运算符语法所建议的那样,=
).也就是说,=
之后的所有内容都是一个表达式,每次调用该方法时都会将其计算为一个值.
Now, unlike other languages you might be familiar with (e.g., C, Java), Scala lets you define methods with an expression (as suggested by the use of the assignment operator syntax, =
). That is, everything after the =
is an expression that will be evaluated to a value each time the method is invoked.
所以,在 Java 中你必须说:
So, whereas in Java you have to say:
public int three() { return 3; }
在 Scala 中,你可以说:
In Scala, you can just say:
def three = 3
当然,表达式通常更复杂(如您的情况).它可能是一个代码块,就像您更习惯看到的那样,在这种情况下,该值是该块中最后一个表达式的值:
Of course, the expression is usually more complicated (as in your case). It could be a block of code, like you're more used to seeing, in which case the value is that of the last expression in the block:
def three = {
val a = 1
val b = 2
a + b
}
或者它可能涉及对其他对象的方法调用:
Or it might involve a method invocation on some other object:
def three = Numbers.add(1, 2)
事实上,后者正是您的具体示例中发生的事情,尽管它需要更多的解释才能理解原因.这涉及到两个魔法:
The latter is, in fact, exactly what's going on in your specific example, although it requires a bit more explanation to understand why. There are two bits of magic involved:
apply
方法,那么你可以把它当作一个函数来对待.例如,你可以说 Add(1, 2)
当你真正的意思是 Add.apply(1,2)
(假设有一个 Add
> 带有 apply
方法的对象,当然).需要明确的是,它不必是使用 object
关键字定义的对象.任何具有合适 apply
方法的对象都可以.def ifWaterBoiling(fn: => Tea)
),那么你可以像 ifWaterBoiling { makeTea }.该块中的代码是惰性求值的(并且可能根本不求值).这相当于编写 ifWaterBoiling({ makeTea })
.{ makeTea }
部分只是定义了一个表达式,该表达式被传入,未计算,用于 fn
参数.apply
method, then you can treat the object as if it were a function. You can say, for example, Add(1, 2)
when you really mean Add.apply(1,2)
(assuming there's an Add
object with an apply
method, of course). And just to be clear, it doesn't have to be an object defined with the object
keyword. Any object with a suitable apply
method will do.def ifWaterBoiling(fn: => Tea)
), then you can invoke the method like ifWaterBoiling { makeTea }
. The code in that block is evaluated lazily (and may not be evaluated at all). This would be equivalent to writing ifWaterBoiling({ makeTea })
. The { makeTea }
part just defines an expression that gets passed in, unevaluated, for the fn
parameter.