對於Python鄉親:
Scala的_*
運營商是Python *-operator或多或少等同。
例
轉換從link由Luigi Plinge提供階例如:
def echo(args: String*) =
for (arg <- args) println(arg)
val arr = Array("What's", "up", "doc?")
echo(arr: _*)
到Python將如下所示:
def echo(*args):
for arg in args:
print "%s" % arg
arr = ["What's", "up", "doc?"]
echo(*arr)
並且兩個給跟隨着克輸出:
What's
up
doc?
的差異:拆封位置參數
雖然Python的*
- 運算符也可以處理用於在固定元數函數位置參數/參數的解壓縮:
def multiply (x, y):
return x * y
operands = (2, 4)
multiply(*operands)
8
D卷板機同樣使用Scala:
def multiply(x:Int, y:Int) = {
x * y;
}
val operands = (2, 4)
multiply (operands : _*)
將失敗:
not enough arguments for method multiply: (x: Int, y: Int)Int.
Unspecified value parameter y.
但它有可能達到同樣的使用Scala:
def multiply(x:Int, y:Int) = {
x*y;
}
val operands = (2, 4)
multiply _ tupled operands
根據Lorrin Nelson這是它如何工作的:
The first part, f _, is the syntax for a partially applied function in which none of the arguments have been specified. This works as a mechanism to get a hold of the function object. tupled returns a new function which of arity-1 that takes a single arity-n tuple.
Futher閱讀:
感謝您指示我鍵入歸屬! – Chris