我知道类型擦除使他们看起来相等,类型,明智的,在运行时,使:我怎样才能DEF FOO [A]之间区分(XS:A *)和DEF FOO [A,B](XS:(A,B)*)?
class Bar {
def foo[A](xs: A*) { xs.foreach(println) }
def foo[A, B](xs: (A, B)*) { xs.foreach(x => println(x._1 + " - " + x._2)) }
}
提供了以下编译器错误:
<console>:7: error: double definition:
method foo:[A,B](xs: (A, B)*)Unit and
method foo:[A](xs: A*)Unit at line 6
have same type after erasure: (xs: Seq)Unit
def foo[A,B](xs: (A, B)*) { xs.foreach(x => println(x._1 + " - " + x._2)
) }
^
但有一个简单的方法是能写:
bar.foo(1, 2, 3)
bar.foo(1 -> 2, 3 -> 4)
,并具有这些调用foo的不同重载版本,而无需显式指定它们:
bar.fooInts(1, 2, 3)
bar.fooPairs(1 -> 2, 3 -> 4)
最直接的方法是为每个类型参数使用上下文绑定的ClassManifest:'def foo [A :ClassManifest](xs:A *)...'。我在下面加入了更多评论的答案。 – 2010-08-12 18:14:45
重载时考虑:http://stackoverflow.com/questions/2510108/why-avoid-method-overloading – 2010-08-17 14:59:38
另请参见:http://stackoverflow.com/questions/3307427/scala-double-definition-2-methods-有同样类型的擦除 – retronym 2010-08-17 21:57:32