ret*_*nym 105
重载使得将方法提升到函数有点困难:
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)
}
Run Code Online (Sandbox Code Playgroud)
您无法有选择地导入一组重载方法中的一个.
尝试应用隐式视图以使参数适应参数类型时,出现歧义的可能性更大:
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("") }
Run Code Online (Sandbox Code Playgroud)
它可以安静地呈现默认参数不可用:
object test {
def foo(a: Int) = 0;
def foo(a: Int, b: Int = 0) = 1
}
Run Code Online (Sandbox Code Playgroud)
单独地,这些原因并不会迫使您完全避免超载.我觉得我错过了一些更大的问题.
UPDATE
证据正在堆积.
更新2
更新3
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...
Run Code Online (Sandbox Code Playgroud)
如果可能的话,Gilad和Jason(反语)给出的原因都是避免超载的理由.吉拉德的理由集中在为什么一般会出现重载问题,而杰森的理由则集中在为什么它在其他Scala功能的背景下存在问题.
对于Jason的列表,我想补充一点,重载与类型推断的交互性很差.考虑:
val x = ...
foo(x)
Run Code Online (Sandbox Code Playgroud)
推断类型的x更改可能会改变foo调用哪个方法.该值的x需求不会改变,只是推断类型的x,这可能发生的各种原因.
由于给出的所有原因(还有一些我确定我忘记了),我认为方法重载应该尽可能少地使用.
| 归档时间: |
|
| 查看次数: |
26911 次 |
| 最近记录: |