【问题标题】:Scala - Generics + implicit conversionScala - 泛型 + 隐式转换
【发布时间】:2011-09-12 15:00:55
【问题描述】:

这个方法是我写的

def compare[U, T <: Comparable[U]](a: T, b: U) = a.compareTo(b)

它适用于 String 和 Integer,但不适用于 Int 或 RichInt。 那么为什么 Int 不能自动转换为 Integer?

【问题讨论】:

    标签: generics scala implicit


    【解决方案1】:

    使用简单的上下文绑定需要编译器在将转换后的值传递给方法之前应用隐式转换。我相信你想要的是这个,而不是:

    def compare[U, T <% Comparable[U]](a: T, b: U) = a.compareTo(b)
    

    这里,'a' 的隐式包装将发生在方法的实现中,所以你应该能够得到你想要的。不过,我并不完全清楚哪些用法让您失望了 - 您应该尝试包括哪些无效的示例,以便我们可以确定何时尝试回答!

    【讨论】:

    • 这绝对是正确的模式。如果可以的话,我建议使用 Scala 的 Ordered 而不是 Comparable。 Ordered 是 Comparable 的子特征,因此它们是兼容的。不过,我确实想知道这对性能的影响。对于整数的每次比较,我们都知道有一个函数调用(可能还有一个对 Integer 的框),这对于排序等繁重的比较操作并不好。
    • 谢谢。那么 <:>
    • <: href="http://stackoverflow.com/questions/2982276/what-is-a-context-bound-in-scala" title="what is a context bound in scala" target="_blank" rel="nofollow">stackoverflow.com/questions/2982276/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多