集合如何对元素类型使用隐式转换? [英] How can collections use implicit conversions on element types?

查看:210
本文介绍了集合如何对元素类型使用隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理此问题时,我想出了以下问题。考虑两个方法定义:

While working on this question, I came up with the following issue. Consider two method definitions:

def foo[T <: Ordered[T]](s : Seq[T]) = s.sorted

def foo[T <% Ordered[T]](s : Seq[T]) = s.sorted

第一个编译,第二个不编译。编译器不知道它可以使用声明的隐式转换来获得 Ordering 。如果我们帮助一点,它的工作原理:

The first one compiles, the second does not. The compiler does not figure out that it can use the asserted implicit conversion to get an Ordering. If we help a bit, it works:

def foo[T <% Ordered[T]](s : Seq[T]) = s.sortWith(_<=_)

编译匿名函数时,隐式转换为find方法< = ,一切都很好。

While compiling the anonymous function the compiler applies the implicit conversion to find method <=, everything is fine.

我没有另一个例子,可以想象类似的问题发生与需要元素有某些属性的集合上的其他函数,如果那些只能通过转换断言。

I do not have another example, but can imagine similar issues to happen with other functions on collections that require elements to have certain properties, if those can only be asserted via conversion.

有什么特别的原因编译器是这样限制的吗?有没有一般方法来解决这些问题? (这里似乎很容易。)有一个解决方法,例如。另一个隐式转换,将 Key [T] 上的属性转换为 T

Is there a particular reason why the compiler is restricted this way? Is there no general way to resolve such issues? (Here it seems easy.) Is there a workaround, e.g. another implicit conversion that translates the property on Key[T] to T?

(注意,如果 T 的具体值最终具有该属性,那么最后的想法可能会有问题;然后我们得到一个模糊的情况) p>

(Note that the last idea can be problematic if a concrete value for T ends up having the property; we then get an ambiguous situation).

推荐答案

scala> implicit def ordering[T <% Ordered[T]] = new Ordering[T]{def compare(x: T, y: T) = x compare y}
ordering: [T](implicit evidence$1: (T) => Ordered[T])java.lang.Object with Ordering[T]

scala> def foo[T <% Ordered[T]](s : Seq[T]) = s.sorted
foo: [T](s: Seq[T])(implicit evidence$1: (T) => Ordered[T])Seq[T]

这篇关于集合如何对元素类型使用隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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