相关疑难解决方法(0)

如何区分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)) }
}   
Run Code Online (Sandbox Code Playgroud)

给出以下编译器错误:

<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)
) }
            ^
Run Code Online (Sandbox Code Playgroud)

但是有一种简单的方法可以写:

bar.foo(1, 2, 3)
bar.foo(1 -> 2, 3 -> 4)
Run Code Online (Sandbox Code Playgroud)

并让这些调用foo的不同重载版本,而不必明确命名它们:

bar.fooInts(1, 2, …
Run Code Online (Sandbox Code Playgroud)

scala overloading type-erasure

15
推荐指数
2
解决办法
2716
查看次数

标签 统计

overloading ×1

scala ×1

type-erasure ×1