Scala 双重定义(2 个方法具有相同的类型擦除) [英] Scala double definition (2 methods have the same type erasure)
问题描述
我用 Scala 写的,它不会编译:
I wrote this in scala and it won't compile:
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 没有对泛型的原生支持,所以我理解这个错误.
I know JVM has no native support for generics so I understand this error.
我可以为 List[String]
和 List[Int]
编写包装器,但我很懒:)
I could write wrappers for List[String]
and List[Int]
but I'm lazy :)
我很怀疑,但是有没有另一种方式来表达 List[String]
与 List[Int]
的类型不同?
I'm doubtful but, is there another way expressing List[String]
is not the same type than List[Int]
?
谢谢.
推荐答案
我喜欢 Michael Krämer 使用隐式的想法,但我认为它可以更直接地应用:
I like Michael Krämer's idea to use implicits, but I think it can be applied more directly:
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)}
我认为这非常易读且直截了当.
I think this is quite readable and straightforward.
[更新]
还有一种简单的方法似乎有效:
There is another easy way which seems to work:
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") }
对于每个版本,您都需要一个额外的类型参数,所以这不会扩展,但我认为对于三个或四个版本来说没问题.
For every version you need an additional type parameter, so this doesn't scale, but I think for three or four versions it's fine.
[更新 2]
对于两种方法,我发现了另一个不错的技巧:
For exactly two methods I found another nice trick:
def foo(list: => List[Int]) = { println("Int-List " + list)}
def foo(list: List[String]) = { println("String-List " + list)}
这篇关于Scala 双重定义(2 个方法具有相同的类型擦除)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!