Scala,柯里化和重载 [英] Scala, currying and overloading

查看:22
本文介绍了Scala,柯里化和重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下内容:

foo(x: String)(y: Int): Int
foo(x: String)(y: Double): Int

Scala 不允许这样的表达.据我所知,原因是 foo("asdf") 没有明确定义的类型(它是 Int => Int 或 Double => Int).

Scala does not allow such expression. As far as I can see, the reason for this is that foo("asdf") does not have a well defined type (it's either Int => Int or Double => Int).

是否有理由不允许这种多类型"函数?

Is there a reason why such "polytyped" functions should not be allowed?

推荐答案

Scala 中的重载解析只考虑第一个参数列表.这就是为什么此列表中的替代方案必须有所不同的原因.这有一个很好的理由:然后我们可以使用解析函数的类型来推断后续参数的类型.这会启用以下习语:

Overloading resolution in Scala takes only the first parameter list into account. That's why alternatives must differ already in this list. There's a good reason for this: We can then use the resolved function's type to infer the type of subsequent arguments. This enables idioms like:

xs.corresponds(ys) { (x, y) => x < y }

注意这里我们需要知道corresponds的类型,以便推断xy的类型.当 corresponds 超载时,这种崩溃将是一种耻辱.

Note that here we need to know the type of corresponds in order to infer the types of x and y. It would be a shame to have this break down when corresponds is overloaded.

这篇关于Scala,柯里化和重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆