为什么“避免方法重载"? [英] Why "avoid method overloading"?
本文介绍了为什么“避免方法重载"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
推荐答案
重载使将方法提升为函数更加困难:
Overloading makes it a little harder to lift a method to a function:
object A {
def foo(a: Int) = 0
def foo(b: Boolean) = 0
def foo(a: Int, b: Int) = 0
val function = foo _ // fails, must use = foo(_, _) or (a: Int) => foo(a)
}
您不能有选择地导入一组重载方法中的一个.
You cannot selectively import one of a set of overloaded methods.
尝试应用隐式视图以使参数适应参数类型时,出现歧义的可能性更大:
There is a greater chance that ambiguity will arise when trying to apply implicit views to adapt the arguments to the parameter types:
scala> implicit def S2B(s: String) = !s.isEmpty
S2B: (s: String)Boolean
scala> implicit def S2I(s: String) = s.length
S2I: (s: String)Int
scala> object test { def foo(a: Int) = 0; def foo(b: Boolean) = 1; foo("") }
<console>:15: error: ambiguous reference to overloaded definition,
both method foo in object test of type (b: Boolean)Int
and method foo in object test of type (a: Int)Int
match argument types (java.lang.String)
object test { def foo(a: Int) = 0; def foo(b: Boolean) = 1; foo("") }
它可以悄悄地使默认参数不可用:
It can quietly render default parameters unusable:
object test {
def foo(a: Int) = 0;
def foo(a: Int, b: Int = 0) = 1
}
分别地,这些原因并不强迫您完全避免超载.我感觉好像错过了一些更大的问题.
Individually, these reasons don't compel you to completely shun overloading. I feel like I'm missing some bigger problems.
更新
证据在堆积.
- 它使规范 复杂化
- 它可以渲染不适合使用的隐式视图,以用于视图边界. >
- 它限制您仅在其中一个重载替代项上引入参数的默认值.
- 由于将键入的参数没有预期的类型,因此您不能传递.
- It complicates the spec
- It can render implicits unsuitable for use in view bounds.
- It limits you to introduce defaults for parameters on only one of the overloaded alternatives.
- Because the arguments will be typed without an expected type, you can't pass anonymous function literals like '_.foo' as arguments to overloaded methods.
更新2
- 您(当前)不能在包对象中使用重载方法.
- 适用性错误为更难诊断您的API的调用者.
- You can't (currently) use overloaded methods in package objects.
- Applicability errors are harder to diagnose for callers of your API.
更新3
- 静态过载解析可以抢劫所有类型安全的API:
scala> object O { def apply[T](ts: T*) = (); def apply(f: (String => Int)) = () }
defined object O
scala> O((i: String) => f(i)) // oops, I meant to call the second overload but someone changed the return type of `f` when I wasn't looking...
这篇关于为什么“避免方法重载"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文