val t = (0f, 0f)
def g(x: Float, y: Float): Unit = {
println(s"g($x, $y)")
}
g(1, 1)
(g _).tupled(t) // working
implicit class Pimps[A <: Object](a: A) {
def f(x: Float, y: Float): A = {
println(s"f($x, $y)")
a
}
}
"".f(1, 1)
("".f _).tupled(t) // not working
这种行为对我来说似乎非常令人困惑和不一致。我得到:
a.sc:18: missing argument list for method f in class Pimps
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `f _` or `f(_,_)` instead of `f`.
val res_6 = ("".f _).tupled(t) // not working
^
Compilation Failed
为什么它在第一种情况下有效,而在第二种情况下不起作用?
如何修复“不工作”行,以便可以使用元组参数调用函数而不解构元组(意味着不使用 ._1
、. _2
或匹配
)?
最佳答案
编辑:
这看起来像SI-8299
这对我来说就像一个错误。如果我们稍微简化一下并显式实例化隐式类,则可以执行以下操作:
implicit class Pimps(a: String) {
def f(x: Float, y: Float): String = a
}
(new Pimps("").f _).tupled // works
查看 ("".f _).tupled
的 -Ytyper-debug 输出:
|-- ("".f: (() => <empty>)).tupled : pt=Unit EXPRmode (site: method main in Implicit)
| | | | |-- ("".f: (() => <empty>)) EXPRmode-POLYmode-QUALmode (site: method main in Implicit)
| | | | | |-- "" EXPRmode-POLYmode-QUALmode (site: method main in Implicit)
| | | | | | \-> String("")
| | | | | [search #1] start `""`, searching for adaptation to pt=String("") => ?{def f: ?} (silent: method main in Implicit) implicits disabled
| | | | | [search #1] considering Pimps
| | | | | |-- Pimps BYVALmode-EXPRmode-FUNmode-POLYmode (silent: method main in Implicit) implicits disabled
| | | | | | \-> (a: String)Pimps
| | | | | [search #1] success inferred value of type String("") => ?{def f: ?} is SearchResult(Pimps, )
| | | | | |-- (a: String)Pimps EXPRmode-POLYmode-QUALmode (silent: method main in Implicit)
| | | | | | \-> Pimps
| | | | | |-- Pimps("").f EXPRmode-POLYmode-QUALmode (site: method main in Implicit)
Implicit.scala:21: error: missing argument list for method f in class Pimps
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `f _` or `f(_,_)` instead of `f`.
("".f _).tupled
虽然编译器正确解析了隐式类,但随后到达方法定义并失败。
您可以通过使用类型归属来解决此问题:
("".f: (Float, Float) => String).tupled
或者通过将函数绑定(bind)到键入的值:
val func: (Float, Float) => String = "".f
func.tupled
关于scala - 如何转换 "pimp"方法来接受元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49776284/