为什么带有单个元组参数的函数文字也接受参数列表?

时间:2017-12-26 15:41:38

标签: scala

我发现了这个有趣的“现象”,如果函数文字被定义为将元组作为其输入参数()。它可以应用于 一个元组 2.与元组

的组件相同类型的参数列表

有人可以向我解释为什么会发生这种情况吗?实际上,我期待2.失败

scala> val foo = (x:List[Int],y:Int) => x.length + y
foo: (List[Int], Int) => Int = <function2>

scala> val bar = (x:(List[Int],Int)) => x._1.length + x._2
bar: ((List[Int], Int)) => Int = <function1>

scala> foo((List(1,2,3),10))
<console>:13: error: not enough arguments for method apply: (v1: List[Int], v2: Int)Int in trait Function2.
Unspecified value parameter v2.
       foo((List(1,2,3),10))
          ^

scala> foo(List(1,2,3),10)
res37: Int = 13

scala> bar(List(1,2,3),10)
res38: Int = 13

scala> bar((List(1,2,3),10))
res39: Int = 13

2 个答案:

答案 0 :(得分:4)

你对括在括号中的参数感到有点困惑,如果参数是一个元组,则不需要它们:

scala> def f(x:(String, String)) = x
f: (x: (String, String))(String, String)

scala> f("a","b")
res9: (String, String) = (a,b)

scala> f(("a","b"))
res10: (String, String) = (a,b)

scala> f((("a","b")))
res11: (String, String) = (a,b)

scala> f(((("a","b"))))
res12: (String, String) = (a,b)

然而,

scala> def g(x: (Int, Int), z:Int) = z
g: (x: (Int, Int), z: Int)Int

scala> g((1,2),3)
res13: Int = 3

scala> g(1,2,3)
<console>:9: error: too many arguments for method g: (x: (Int, Int), z: Int)Int
          g(1,2,3)

答案 1 :(得分:2)

抱歉,我没有声誉添加评论,但我建议查找自动翻译。

原因

scala> bar(List(1,2,3),10)
res38: Int = 13

工作是因为两个参数被转换为元组(List(1,2,3),10),以符合bar的参数类型。

有编译标志警告(-Ywarn-adapted-args)或禁止(-Yno-adapted-args)这样的行为。