How can collections use implicit conversions on element types?

本小妞迷上赌 提交于 2019-12-19 08:31:31

问题


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

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(_<=_)

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.

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?

(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).


回答1:


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]



回答2:


% scala29
Welcome to Scala version 2.9.0.r24168-b20110202012927 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

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

scala>

By the way, re "here it seems easy", it wasn't. Implicits like these enjoy diverging and they were pretty determined.



来源:https://stackoverflow.com/questions/4876079/how-can-collections-use-implicit-conversions-on-element-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!