我用 scala 编写了这个,但它无法编译:
class TestDoubleDef{
def foo(p:List[String]) = {}
def foo(p:List[Int]) = {}
}
编译器通知:
[error] double definition:
[error] method foo:(List[String])Unit and
[error] method foo:(List[Int])Unit at line 120
[error] have same type after erasure: (List)Unit
我知道 JVM 没有对泛型的 native 支持,所以我理解这个错误。
我可以为 List[String]
和 List[Int]
编写包装器,但我很懒:)
我很怀疑,但是是否有另一种方式来表达 List[String]
与 List[Int]
的类型不同?
谢谢。
最佳答案
我喜欢 Michael Kramer 使用隐式的想法,但我认为它可以更直接地应用:
case class IntList(list: List[Int])
case class StringList(list: List[String])
implicit def il(list: List[Int]) = IntList(list)
implicit def sl(list: List[String]) = StringList(list)
def foo(i: IntList) { println("Int: " + i.list)}
def foo(s: StringList) { println("String: " + s.list)}
我认为这是非常可读且简单的。
[更新]
还有另一种似乎有效的简单方法:
def foo(p: List[String]) { println("Strings") }
def foo[X: ClassTag](p: List[Int]) { println("Ints") }
def foo[X: ClassTag, Y: ClassTag](p: List[Double]) { println("Doubles") }
对于每个版本,您都需要一个额外的类型参数,因此这无法扩展,但我认为对于三个或四个版本来说就可以了。
[更新2]
对于两种方法,我发现了另一个不错的技巧:
def foo(list: => List[Int]) = { println("Int-List " + list)}
def foo(list: List[String]) = { println("String-List " + list)}
关于Scala双重定义(2个方法具有相同的类型删除),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3307427/