scala - how to reference a specific function where two functions in scope have the same name
问题描述
Given that we have two functions in scope with the same name but a different parameter list. How can I distinguish one from the other, such as in the case of trying to access the tupled
function
Example:
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
Simplifying the problem to function literals yields:
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 _
^
But the explicit type annotation in the function literal example manages to solve the problem, where as for the apply
method above in the context of tupled
did not work
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
解决方案
Here is the way you can achieve this
val t1 = (f(_: String, _: Long)).tupled
val t2 = (f(_: Int, _: Long)).tupled
output
t1: ((String, Long)) => String = scala.Function2$$Lambda$1188/922196321@3994b698
t2: ((Int, Long)) => String = scala.Function2$$Lambda$1188/922196321@4249db51
推荐阅读
- docker - 在 Dockerfile 中添加自定义 openssl.cnf 以生成 SSL
- python - 具有复数元素的 Numpy 矩阵向量乘法
- reactjs - Reactjs屏幕不刷新,更新时总是落后一个循环
- arrays - 在常见的 lisp 中,使用 '#(...) 或仅使用 #(...) 创建向量有什么区别?
- python - SQL 中的中间聚合函数和数据操作
- azure - 有没有办法使用二头肌将 Azure 防火墙连接到 Front Door 高级策略?
- swift - xcode12 如何将.md 文件的字体更改为等宽字体?
- javascript - 展平嵌套的 JSON 对象
- python - 一次将多个 tkinter 菜单项设置为“正常”的最有效方法是什么?
- python - 你如何在 Numpy 中创建一个(有时)参差不齐的数组?