:
Scalaの_*
オペレータはPythonの*-operatorの多かれ少なかれ同等です。パイソンの
def echo(args: String*) =
for (arg <- args) println(arg)
val arr = Array("What's", "up", "doc?")
echo(arr: _*)
は次のようになり:
def echo(*args):
for arg in args:
print "%s" % arg
arr = ["What's", "up", "doc?"]
echo(*arr)
との両方がfollowinを与えるLuigi Plingeによって提供linkからScalaの例を変換
例
G出力:
What's
up
doc?
差:アンパック位置パラメータ
Pythonの*
演算子はまた、固定アリティ関数の位置パラメータ/パラメータのアンパックに対処することができるが:
def multiply (x, y):
return x * y
operands = (2, 4)
multiply(*operands)
8
D Scalaのと同じことをoing:
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 (operands : _*)
は失敗します
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読み:
私はタイプのascriptionを指してくれてありがとう! – Chris