我知道類型擦除使他們看起來相等,類型,明智的,在運行時,使:我怎樣才能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