Scala双精度(2种方法具有相同的类型擦除) [英] Scala double definition (2 methods have the same type erasure)

查看:568
本文介绍了Scala双精度(2种方法具有相同的类型擦除)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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] 'm lazy:)

I could write wrappers for List[String] and List[Int] but I'm lazy :)

我有疑问,但是有另一种方式表达 List [String]

I'm doubtful but, is there another way expressing List[String] is not the same type than List[Int]?

谢谢。

推荐答案

我喜欢MichaelKrä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.

[Update]

有另一种简单的方法似乎工作:

There is another easy way which seems to work:

def foo(p: List[String]) { println("Strings") }
def foo[X: ClassManifest](p: List[Int]) { println("Ints") }
def foo[X: ClassManifest, Y: ClassManifest](p: List[Double]) { println("Doubles") }

[Update 2] 这是一个非常简单的方法,

[Update 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆