鉴于我们在作用域中有两个函数,它们的名称相同但参数列表不同。如何区分彼此,例如在尝试访问tupled
函数的情况下
示例:
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f(s: String, l: Long): String = ???
def f(i: Int, l: Long): String = ???
val t:((String, Long)) => String = f.tupled
// Exiting paste mode, now interpreting.
<pastie>:15: error: ambiguous reference to overloaded definition,
both method f of type (i: Int, l: Long)String
and method f of type (s: String, l: Long)String
match expected type ?
val t:((String, Long)) => String = f.tupled
将问题简化为函数文字可得出:
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f(i: Int, l: Long): String = ???
def f(s: String, l: Long): String = ???
val g = f _
// Exiting paste mode, now interpreting.
<pastie>:15: error: ambiguous reference to overloaded definition,
both method f of type (s: String, l: Long)String
and method f of type (i: Int, l: Long)String
match expected type ?
val g = f _
^
但是函数文字示例中的显式类型注释设法解决了这个问题,至于上述apply
上下文中的tupled
方法不起作用
scala>
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f(s: String, l: Long): String = ???
def f(i: Int, l: Long): String = ???
val g: (String, Long) => String = f _
// Exiting paste mode, now interpreting.
f: (s: String, l: Long)String <and> (i: Int, l: Long)String
f: (s: String, l: Long)String <and> (i: Int, l: Long)String
g: (String, Long) => String = $$Lambda$1458/794413935@60cbba57
答案 0 :(得分:3)
这是您实现这一目标的方法
val t1 = (f(_: String, _: Long)).tupled
val t2 = (f(_: Int, _: Long)).tupled
输出
t1: ((String, Long)) => String = scala.Function2$$Lambda$1188/922196321@3994b698
t2: ((Int, Long)) => String = scala.Function2$$Lambda$1188/922196321@4249db51
答案 1 :(得分:0)
我发现了针对tupled
问题的以下破解方法:
scala> :paste
// Entering paste mode (ctrl-D to finish)
def f(s: String, l: Long): String = ???
def f(i: Int, l: Long): String = ???
val g: (String, Long) => String = f _
val t = g.tupled
// Exiting paste mode, now interpreting.
f: (s: String, l: Long)String <and> (i: Int, l: Long)String
f: (s: String, l: Long)String <and> (i: Int, l: Long)String
g: (String, Long) => String = $$Lambda$1476/1981627424@172f2717
t: ((String, Long)) => String = scala.Function2$$Lambda$259/530042637@bda4cbe